Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ImageField passing a callable to 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?

like image 557
9-bits Avatar asked Feb 01 '12 04:02

9-bits


2 Answers

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)
like image 168
Mixologist Avatar answered Oct 31 '22 21:10

Mixologist


You can use staticmethod 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 like here).

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)
like image 33
Mariusz Jamro Avatar answered Oct 31 '22 21:10

Mariusz Jamro