3

There are two models:

class BaseImage(models.Model):
    description = models.CharField(max_length=200)
    image = models.ImageField(upload_to='images')

    class Meta:
        abstract = True

class PostImage(BaseImage):
    in_text = models.BooleanField()

    def __init__(self, *args, **kwargs):
        super(BaseImage, self).__init__(*args, **kwargs)
        self.image.upload_to = 'images/news/%Y/%m/%d'

How can I set upload_to property in the base model? This my attempt doesn't work:

        self.image.upload_to = 'images/news/%Y/%m/%d'
1

1 Answer 1

8

What I can suggest is to write function to get upload to method from instance e.g.

in models.py

#default method to get file upload path
def get_upload_to(instance, filename):
    return instance.get_upload_to_path(filename)

class BaseImage(models.Model):
    description = models.CharField(max_length=200)
    image = models.ImageField(upload_to=get_upload_to)

    class Meta:
        abstract = True
    #method on the class to provide upload path for files specific to these objects
    def get_upload_to_path(instance, filename):
         return 'images/'+filename

class PostImage(BaseImage):
    in_text = models.BooleanField()

    #method to provide upload path for PostImage objects
    def get_upload_to_path(instance, filename):
    #change date.year etc to appropriate variables
         return 'images/news/%Y/%m/%d' % (date.year, date.month, date.day)
Sign up to request clarification or add additional context in comments.

3 Comments

I understand the idea, but your code is not clear enough. Please, make corrections for other people.
@art.zhitnik Added some comments, do they help?
If I understood right, instead of upload_to='images' must be upload_to=get_upload_to, and class methods must be named as get_upload_to_path, not get_upload_to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.