Reputation: 1025
I have a model such as this:
class MyModel(models.Model):
red = models.ForeignKey(Anothermodel)
blue = models.ImageField(upload_to='folder')
Would it be possible for 'folder' to be set to the value of field 'red'?
My purpose is that when a user uploads an image, it is automatically stored on a folder that has some field from that very same model as its name.
Thank you in advance.
Upvotes: 2
Views: 908
Reputation: 13058
Yes, upload_to
also takes a callable (e.g. a function):
def blue_upload_to(instance, filename):
folder = instance.red.some_field
return folder + os.sep + filename
class MyModel(models.Model):
red = models.ForeignKey(Anothermodel)
blue = models.ImageField(upload_to=blue_upload_to)
The documentation provides some additional examples: https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.FileField.upload_to
Upvotes: 3