9-bits
9-bits

Reputation: 10765

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?

Upvotes: 6

Views: 5841

Answers (2)

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

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)

Upvotes: 2

Mixologist
Mixologist

Reputation: 111

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)

Upvotes: 11

Related Questions