Django ImageField pasando un invocable a upload_to

I'm trying to pass a custom upload_to function to my models imageField but I'd like to define the function as a model function....is that possible?

class MyModel(models.Model):
    ...
    image = models.ImageField(upload_to=self.get_image_path)
    ...

    def get_image_path(self, filename):
        ...
        return image_path

Now i know i can't reference it by 'self' since self doesn't exist at that point...is there a way to do this? If not - where is the best place to define that function?

preguntado el 01 de febrero de 12 a las 04:02

Yeah, look at the link that Paulo mentions - it shows it clearly there (no self., define the callable as a function in the models.py) -

Looks like my answer is here after all: stackoverflow.com/questions/1190697/… -

2 Respuestas

So Just remove "@classmethod" and Secator's code will work.

class MyModel(models.Model):

    # Need to be defined before the field    
    def get_image_path(self, filename): 
        # 'self' will work, because Django is explicitly passing it.
        return filename

    image = models.ImageField(upload_to=get_image_path)

Respondido 15 Feb 13, 03:02

Puede usar el método estático decorator to define the upload_to inside of a class (as a static method). Hovever it has no real benefit over typical solution, which is defining the get_image_path before class definition como aquí).

class MyModel(models.Model):

    # Need to be defined before the field
    @classmethod       
    def get_image_path(cls, filename): 
        # 'self' will work, because Django is explicitly passing it.
        return filename

    image = models.ImageField(upload_to=get_image_path)

Respondido 26 Feb 19, 10:02

@Secator: I tried this in my own code but it's not actually calling the method-- for the file location, I'm getting "Currently: <classmethod object at 0x9bf4944>/o7pDX.jpg" - Colleen

@Colleen, it's converting my staticmethod to a string too. Looks like the method has to be a direct attribute of the module (or of some module). - mjumbewu

it works find if you just define get_image_path as a normal method without @classmethod - laike9m

en un parche de @classmethod, the first param should be the class not the object. To make it less confused, I think you should use cls en lugar de self - Nathan Do

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.