My goal is to be able to upload a picture via the admin page, and have the picture be automatically placed in a directory of my choosing. I want the upload path of the picture that I choose in the admin page to use the name of the restaurant in the path. For example, if the name of the restaurant is IHOP, I would want the upload_path to be, say, ./myapp/static/myapp/images/IHOP/. My current code is as follows:
Models.py
class Restaurant(models.Model):
...
name = models.CharField(max_length=100, default='')
header_image = models.ImageField()
def save(self, *args, **kwargs):
upload_path = 'some_path'
self.header_image = models.ImageField(upload_to=upload_path + name)
super(Restaurant, self).save(*args, **kwargs)
However, when I try to run this (save an item via the admin page), I get the following error:
ImageField has no attribute '_committed'.
I cannot directly reference the name variable in my header_image initialization because the class has not yet been instantiated (I have tried this approach).
Is there a way that I can change the upload_to paramater of the ImageField after I initialize the field? Similarly, is there any solution that will allow me to make the upload file path of the image dependent on the name of the restaurant?
Lastly, I would like to note that a similar question has been asked, but it is not the same scenario. In the other question, the asker wanted to use a field from an entirely different model. In this scenario, I am looking to use a field (name) to create another field (header_image).
Aucun commentaire:
Enregistrer un commentaire