← Back to all tutorials
Django TutorialEpisode 16

Article Detail Template

Build the article detail page — display the full article content, author, date, and add a link back to the article list.

Article Detail Template

Let us create the detail page that displays a full article when the user clicks on a title from the list.

The Detail View

# articles/views.py
from django.shortcuts import render
from .models import Article

def article_detail(request, slug):
    article = Article.objects.get(slug=slug)
    return render(request, 'articles/article_detail.html', {
        'article': article
    })

The Detail Template

<!-- templates/articles/article_detail.html -->
{% extends 'base_layout.html' %}

{% block content %}
    <div class="article-detail">
        <h2>{{ article.title }}</h2>
        <p class="meta">
            Written by {{ article.author }} | {{ article.date|date:"M d, Y" }}
        </p>
        <div class="article-body">
            {{ article.body }}
        </div>
        <a href="{% url 'articles:list' %}">← Back to articles</a>
    </div>
{% endblock %}

Linking from the List Page

<!-- In article_list.html -->
{% for article in articles %}
    <div class="article">
        <h2>
            <a href="{% url 'articles:detail' slug=article.slug %}">
                {{ article.title }}
            </a>
        </h2>
        <p>{{ article.snippet }}</p>
        <p>{{ article.date|date:"M d, Y" }}</p>
    </div>
{% endfor %}

Handling 404s

# Better approach — returns 404 if not found
from django.shortcuts import get_object_or_404

def article_detail(request, slug):
    article = get_object_or_404(Article, slug=slug)
    return render(request, 'articles/article_detail.html', {
        'article': article
    })

get_object_or_404 raises a 404 error if no article matches the slug, instead of crashing with a server error.

Key Takeaways

  • The detail view gets a single article by slug and passes it to the template
  • Use {% url 'name' slug=article.slug %} to link to detail pages
  • get_object_or_404 is safer than objects.get() — returns a proper 404 page
  • The detail template extends the base layout and fills in the content block