I have an abstract model class UploadItem for handling uploaded files. I want each subclass to be able to define the upload_to path. For this, i pass a callback to the constructor of FileField.
This is an example:
class UploadItem(models.Model):
file = models.FileField(upload_to=UploadItem.get_directory)
class Meta:
abstract = True
# I want videos to be storred in 'videos/' directory
class Video(UploadItem):
def get_directory(self, instance, filename):
return 'videos/'
But this doesn't work, i am getting this error:
file = models.FileField(upload_to=UploadItem.get_directory)
NameError: name 'UploadItem' is not defined
This can be done in a similar fashion with some tweaks if you need to use base class properties as part of a subclass:
And then in subclass:
This way you will have
upload_to
that equals:files
forUploadItem
files/videos
forVideo
Might be useful for more complex objects that require to share some common base property.
The error is natural given that at the time of evaluating
the
UploadItem
class is not yet defined. You can do the following to make it work:This won't solve all your problems though. Adding (or overriding) a method
get_directory
in theVideo
class will not change theupload_to
property of thefile
attribute of the model.Update
The documentation says that the
upload_to
can be a callable.Given this we can write a custom call back function like this:
Instance
here will be the instance of the respective model. For this to work each model instance should have a category field. We can add one in the body of the model.