[Answer]-Display all model data inside html page

0👍

I figured out the solution after many long annoying hours of trying everything. I feel dumb but I want to spare the next guy the massive pain in the two-pack.

This is what I did:

In the Views.py, I changed the view function for this page FROM this:

def view_all_categories(request):
    context = {'Category' : Category}
    return render(request, 'store/see_all_categories.html', context)

TO this

def view_all_categories(request):
    all_cats = Category.objects.all().order_by('id')
    context = {'all_categories' : all_cats}
    return render(request, 'store/see_all_categories.html', context)

and in the page see_all_categories.html itself, I changed it (from the question) TO this:

{% extends 'base.html' %}
{% load staticfiles %}

{% block content%}
    {% for cat in all_categories %}
         <p>{{ cat.name }}</p>
    {% endfor %}
{% endblock content %}

And now it works!!

1👍

You want to display a list of the categories. I assume your Category model owns an attribute named “title” which is the representation of your Category.

If you’re using Django template engine or Jinja2, you can make a for loop inside your template like this :

{% for cat in Category.objects.all %}
<a href="#">{{ cat.title }}</a>
{% endfor %}

As a troubleshooting, I’d suggest you didn’t pass your Category model to your template, that is not done automatically. You have to add your model to the context before rendering the template.

As mentionned in the comments, here is doc for template rendering with Django templates.
Django Template Guide

To add your model to the context you can follow this guide.
I don’t intend to help you further because I lack of information and that may vary a LOT according to your settings. (Class Based views ? Function based views ? What kind of template are you using… And so on)

👤Depado

Leave a comment