2

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?

Snowball
  • 35
  • 5

2 Answers2

1

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'
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • I already tryed, but then I get this Error `TypeError at /detail/5/ 'Article' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/detail/5/` – Snowball Mar 26 '20 at 19:12
  • Maybe is this because my URL? `path('detail//', views.MyDetailView.as_view(), name='detail'),` – Snowball Mar 26 '20 at 19:13
  • @Snowball: for a `DetailView` the item is of course not iterable, since *one* article, well is not a collection of iterables. – Willem Van Onsem Mar 26 '20 at 19:14
  • @Snowball: give you have a `DetailView`, why do you use a `{% for ... %}` loop in the first place? – Willem Van Onsem Mar 26 '20 at 20:31
0

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}}

JohnJerry
  • 86
  • 2
  • 9