Home > Blockchain >  How can I iterate through each item in a database and display them in divs on my html page with djan
How can I iterate through each item in a database and display them in divs on my html page with djan

Time:11-18

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.

CodePudding user response:

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.

  • Related