Home > Software design >  DJANGO - Upload image and then display on template
DJANGO - Upload image and then display on template

Time:09-17

I'm trying to display the 'plant_image' within the for loop on dashboard.html.

I can get all other fields to display but the image will not.

I understand there is some difference between development and production, but I just want to have it work in development for the moment. If someone could explain how to make this work, I would be very grateful.

model.py

  class Plant(models.Model):
        plant_name = models.CharField(max_length=30)
        plant_image = models.ImageField(upload_to ='upload/', height_field=None, width_field=None, max_length=None)

dashboard.html - template

{% for plant in plants %}
    <p>/{{plant.plant_name}}</p>
    <img src="{{plant.plant_image}}" alt="Plant Image" width="250" height="250">
{% endfor %}

views.py

def dashboard(request):
    plants = Plant.objects.all()
    return render(request, 'dashboard.html', {'plants': plants})

urls.py

urlpatterns = [
    path('', views.dashboard, name='dashboard'), 
]

CodePudding user response:

Hi on your HTML you should give image url to display image

    {% for plant in plants %}
        <p>{{plant.plant_name}}</p>
        <img src="{{plant.plant_image.url}}" alt="Plant Image" width="250" height="250">
    {% endfor %}

try on HTML if it still don't working you should write property to your models.py

class Plant(models.Model):
    plant_name = models.CharField(max_length=30)
    plant_image = models.ImageField(upload_to ='upload/', height_field=None, width_field=None, max_length=None)

    @property
    def plant_image_url(self):
        return '%s%s' % (settings.HOST, self.plant_image.url) if self.plant_image else ''

and on your html

{% for plant in plants %}
        <p>{{plant.plant_name}}</p>
        <img src="{{plant.plant_image_url}}" alt="Plant Image" width="250" height="250">
    {% endfor %}

CodePudding user response:

In image src you will have to use "plant.plant_image.url" otherwise it will not work.

So, in dashboard.html - template, you will have to write as follows:-

    {% for plant in plants %}
        <p>{{plant.plant_name}}</p>
        <img src="{{plant.plant_image.url}}" alt="Plant Image" width="250" height="250">
    {% endfor %}

To retrieve the "image url" you will have to use "plant.plant_image.url".

  • Related