Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I iterate through each item in a database and display them in divs on my html page with django?

I have some code written to find the first post in the database and output it to my page, but I’, not sure how to go about iterating through the database. I’ve done similar things before but this is my first time using django and bootstrap.

My view currently looks like this:

def gallery_view (request):
    obj = GalleryPost.objects.get (id =1)
    context = {
        'object' : obj
     }
    return render(request, "gallery.html", context)

This works well enough for 1 object but as you can see it takes a set ID of 1, so I need to somehow iterate this to fetch every item from my DB and somehow output them properly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

View:

def gallery_view(request):
    qs = GalleryPost.objects.all()
    context = {
        'objects' : qs
    }
    return render(request, "gallery.html", context)

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% for object in objects %}
        <div>
            {{object}}
        </div>
    {% empty %}
        <p>No objects found</p>
    {% endfor %}
</body>
</html>

Instead of .all() you can also use .filter() to filter the queryset.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading