Django template for loop is empty

1.2k Views Asked by At

I am trying to build a detail view in django, but nothing is displayed in the template.

views.py

class MyDetailView(DetailView):
    model = Article
    template_name = 'detail.html'

detail.html

{% extends 'base.html' %}
{% load i18n %}
{% endblock %}

{% block content %}

{% for item in itemlist %}
{{item.pk}}
{{item.title}}

{% empty %}
There are no items in this list

{% endfor %}
{% endblock %}

Why is nothing displayed in the template here?

2

There are 2 best solutions below

4
On

You do not pass a item with the name itemlist to the template in a DetailView. In a ListView (which looks more appropriate), it will by default use a context variable named object_list. Since the variable is not present, the {% for … %}…{% endfor %} template block [Django-doc] will be resolved to the empty string.

If you want to pass the queryset of Articles to the context through the itemlist name, you can set the context_object_name attribute [Django-doc]:

from django.views.generic import ListView

class MyDetailView(ListView):
    model = Article
    template_name = 'detail.html'
    context_object_name = 'itemlist'
1
On

As Willem told you in the comment, you're in a details view so you don't need a for loop to iterate , you can just show the details in the template like: {{item.pk}}