简体   繁体   中英

Default Image for ImageField

Hi I'm trying to set up a default image for a ToDo List in Django. I have a the images under static/images . Now I'm trying to add a function where you can add tasks. in thid function I can choose a image. If no image is chosen, the image will become a default image ex. Placeholder.png

I tried creating a if else loop in models.py but that does not work either. Showing chosen images does work.

models.py:

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField()
    description = models.CharField(max_length=255, null=True)
    image = models.ImageField(null=True, blank=True)
    technologie = models.CharField(max_length=255, null=True)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        if self.image:
            return self.image.url
        else:
            return "static/images/Placeholder.png"

Now my question is how can I set Placeholder.png from the static directory as a default for ImageField?

You can try this as this work fine for me hope it would be help you as well:)

image = models.ImageField(upload_to='images',default="images/Placeholder.png")

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