简体   繁体   中英

Django model's attribute to dynamic change default value of ImageField

I have the following model:

class ImageTest(models.Model):
    pic = models.ForeignKey(Pic, on_delete=models.CASCADE)
    image_field = models.ImageField(upload_to='images/', default=' << HERE I WANT TO CHANGE DYNAMIC >>')

When adding a ImageTest Object, I select a pic from my existing Pic objects. But then, I want to auto-complete the image_field with a image from path that corresponds to the Pic object.

For example:

  • If I choose the Pic Object #1 (foreign key) -> my path for imageField to be: images/pic1.jpg

  • If I choose the Pic Object #2 -> my path to be images/pic2.jpg and so on.

How can I make this to be done the moment I choose the Pic object, not when pressing Save button?

I'm not sure setting the default here is the right way to go. I don't think you can change the default value without migrating the database. Instead, I'd maybe override the save() method of the ImageTest model to set the image_field based on the pic value.

Something like this maybe:

class ImageTest(models.Model):
    pic = models.ForeignKey(Pic, on_delete=models.CASCADE)
    image_field = models.ImageField(upload_to='images/', blank=True)

    def save(self, *args, **kwargs):
        if self.pic:
            self.image_field = self.pic.image_path # whatever the corresponding pic field is
        super().save(*args, **kwargs)

You can also implement the save() method so the image_field only gets set when the ImageTest is being created by checking for pk as this will not be set until super().save() is called.

if not self.pk and self.pk:
    self.image_field = self.pic.image_path # whatever the corresponding pic field is

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM