I am pretty new to django and now I'm currently learning how to access images in database and display it using html. I want to put the images as elements in a list for further styling and making the page responsive using css but I don't want to write each and every image as a list item as there are more than 100 images in database. I've tried the below code but its not displaying images as a list. Please do suggest if any better way of doing it. I have image
as a model in my models.py
.
<div class='gallery'>
{% for x in photo %}
<ul>
<li><img class="images" src="{{x.image.url}}"/></li>
</ul>
{% endfor %}
</div>
This is the model for reference:
from django.db import models
class Photo(models.Model):
photo_uploader = models.CharField(max_length=50)
desc = models.CharField(max_length=300)
image = models.ImageField(upload_to="home/images")
This is the view:
def profile(request):
username = None
if request.user.is_authenticated:
photos_to_show = []
username = request.user.username
photos = Photo.objects.filter(photo_uploader=username)
return render(request, 'profile.html', {'name': username, 'photo': photos})
The <ul>
tags should be placed outside the loop, otherwise you each time start a new <ul>
and end that </ul>
per image:
<div class='gallery'>
<ul>
{% for x in photo %}
<li><img class="images" src="{{ x.image.url }}"/></li>
{% endfor %}
</ul>
</div>