Django: Read image path field from MySQL

Viewed 113

im curently making a mini product eshop for my studies. So I have the image path of products in MySQL database like LOAD_FILE(C:\\product.jpg) and I want to access the image from my Django project.

I have 2 questions. 1st, what Model Field should I use to read the image from the database's image path. And 2nd one how to read this image?

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.DecimalField(max_digits=7,decimal_places=2)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url
1 Answers

The Models.ImageField is perfect for this. You don't need to it like this. Simply get your image in the template using {{ Product.image.url }} inside an img tag. Use If condition in templates such as {% if Product.image.url is not null %} <Show the picture> {% else %}<show some default image or show some text> {% endif %}

Related