Reputation: 99
I want to upload images to the django server using my application and the folder/directory_name to which the image has to be uploaded, should be auto populated using the foreignkey relationship that my models are sharing
My models classes are as follows,
class Event(models.Model):
event_name = models.CharField(max_length=200)
event_desc = models.CharField(max_length=5000)
def __str__(self):
return self.event_name
class Image(models.Model):
event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
image_name = models.CharField(max_length=200)
image = models.ImageField(upload_to='events/{}'.format("something"))
def __str__(self):
return self.image_name
the something
in the models.ImageField function has to be replaced by the event_name
dynamically and the value for event_name
should be populated dynamically.
Upvotes: 2
Views: 77
Reputation: 476574
You can pass a callable to the upload_to=…
parameter [Django-doc]: which contains a reference to the model object, so you can redefine this to:
class Image(models.Model):
def upload_image_to(instance, filename):
return f'events/{instance.event_id.event_name}/{filename}'
event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
image_name = models.CharField(max_length=200)
image = models.ImageField(upload_to=upload_image_to)
def __str__(self):
return self.image_name
You can change the filename as well, you can rewrite the upload_image_to
function to:
def upload_image_to(instance, filename):
ext = filename.rsplit('.', 1)[-1]
return f'events/{instance.event_id.event_name}/{instance.image_name}.{ext}'
Here we thus split right-to-left, and only retain the last part as extension.
Note: Normally one does not add a suffix
_id
to aForeignKey
field, since Django will automatically add a "twin" field with an_id
suffix. Therefore it should bescene
, instead of.scene_id
Upvotes: 1