Class attribute inheritance in Django models

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'

Answers


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)

Need Your Help

How to set checkbox by default checked in checkbox dialog

android android-dialog

I have a checkbox dialog i want to set some of its values by deafult checked.

Google Drive SDK asking for permissions

.net oauth-2.0 google-drive-sdk

I have a test app created in .NET with the DrEdit example. I have published this to the testusers group so I can open it in Chromes webstore. But everytime I access it it will ask for permissions "...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.