How to use detail view function-based views in Django

Key takeaways:

  • Detail views are used to display detailed information about a specific instance of a model by retrieving it from the database using a unique identifier (the primary key).

  • Function-based views (FBVs) fetch the relevant data and pass it to a template for rendering, offering a straightforward approach to display data.

  • Proper URL patterns are essential for mapping views to specific URLs. For example, the URL pattern path('book/<int:pk>/', views.book_detail) captures the primary key of a book to retrieve and display its details.

  • Django templates dynamically render the fetched data (such as title, author, publication date) using Django’s template language, ensuring that the correct information is displayed on the page.

Imagine you’re building an e-commerce website, where a user clicks on a product to view its details, such as the name, description, price, and images. How can we efficiently fetch and display this information using Django? This is where detail views come in handy. Let’s learn how to create detail views using function-based views to achieve this.

What is a detail view in Django?

Django provides an intuitive and robust way to handle detailed data retrieval from models. A detail view is a display that shows the specific details of a particular database record. It is used to present various types of data on a single page or view. For instance, when a user accesses a product page, the detail view fetches the relevant product from the database and presents its information.

Installation

Before we dive into using detail views, let’s set up Django and ensure the necessary environment is ready. Follow these steps:

Step 1: Install Python

Make sure you have Python installed on your system. To verify the installation, run:

python3 --version

Step 2: Install Django

Use pip to install Django:

pip install django

After installation, check the Django version to ensure it is installed correctly:

python3 -m django --version

Step 3: Creating a Django project

Create a new Django project by running:

django-admin startproject detail_view_demo
cd detail_view_demo

This creates a new Django project named detail_view_demo with essential files and a directory structure for development.

Step 4: Create a new app

Inside the project, create a new app for your models and views:

python manage.py startapp myapp

Step 5: Run the server

Start the development server to ensure everything is working:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser to confirm the setup.

Setting up the project

After installing Django and creating a project, we need to configure the project and app to use detail views effectively.

Step 1: Configure the app

Open the settings.py file in the detail_view_demo directory and add myapp to the INSTALLED_APPS list:

INSTALLED_APPS = [
...
'myapp',
]
Add myapp to the INSTALLED_APPS in the settings.py file

Step 2: Create the Book model

To store the details of the books, we’ll create a Book model in the myapp/models.py file:

from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
publication_date = models.DateField()
description = models.TextField()
def __str__(self):
return self.title
The myapp/models.py file

In the above code:

  • Line 1: We import the models module from django.db.

  • Lines 3–10: We define a class named Book that inherits from models.Model. In this class:

    • Lines 4–7: We define the title, author, publication date, and description to store the book details.

    • Lines 9–10: We define a special method called __str__. The __str__ method is called when we print an instance of the Book model or when it is displayed in the Django admin interface. In this case, it returns the title of the book.

Step 3: Apply migrations

By default, Django uses SQLite as its database. You don’t need to make any changes unless you prefer another database. To apply database migrations, run:

python3 manage.py makemigrations
python3 manage.py migrate

Step 4: Create the function-based view (FBV)

In Django, we can use a function-based view to retrieve and display the details of a book. Let’s write a view that fetches a single book from the database and displays it.

  1. Open myapp/views.py and write the following code:

from django.shortcuts import render, get_object_or_404, redirect
from .models import Book
from .forms import BookForm
# Homepage view: lists all books
def home(request):
books = Book.objects.all()
return render(request, 'home.html', {'books': books})
# Detail view: shows book details
def detail(request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, 'detail.html', {'book': book})
# Create view: adds a new book
def create(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = BookForm()
return render(request, 'create.html', {'form': form})
The myapp/views.py file

In the above code:

  • Lines 6–8: We define the home view to display all the books stored in the database.

  • Lines 11–13: We define the detail view to display the details of a specific book based on its primary key (pk).

  • Lines 16–24: We define the create view to handle the creation of new books through a form, saving the form data to the database and redirecting the user to the homepage upon success.

Step 5: Create a form for book creation

In myapp/forms.py, create a BookForm class using Django’s ModelForm:

from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'publication_date', 'description']
The myapp/forms.py file

In the above code, we define the BookForm class, which inherits from forms.ModelForm. This allows us to generate a form based on the Book model, and inside the inner Meta class, we specify that the form is based on the Book model and include the fields title, author, publication_date, and description.

Step 6: Configure the URL patterns

Now, let’s add a URL pattern to link to the book detail view.

  1. In the myapp/urls.py file, add the following code:

from django.urls import path
from .views import home, detail, create
urlpatterns = [
path('', home, name='home'),
path('book/<int:pk>/', detail, name='detail'),
path('create/', create, name='create'),
]
The myapp/urls.py file

In the above code, we define the urlpatterns list, which maps specific URLs to their corresponding views. We map the root URL (/) to the home view, URLs like /book/1/ or /book/2/ to the detail view, and the URL /create/ to the create view.

  1. In the detail_view_demo/urls.py file, add the following code:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
The detail_view_demo/urls.py file

In the above code, we map the URL admin/ to the Django admin site. We also include the urls.py file from the myapp app. It means that any URL pattern defined in myapp.urls will be included here, and the root URL (/) will be handled by the URLs defined in myapp.urls.

Step 7: Create the template

Now, we’ll create the template to display the book details.

  1. Create a new folder called templates inside your myapp directory. Inside this folder, create a file named detail.html.

  2. Add the following code to home.html. This HTML code creates a webpage that displays a list of books with their titles and authors. Each book title is a clickable link that takes the user to a detailed view of the book. Additionally, there's a link at the top of the page to add a new book to the list.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Books List</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #2c3e50;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
}
a {
text-decoration: none;
color: #3498db;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Book List</h1>
<a href="{% url 'create' %}">Add New Book</a>
<ul>
{% for book in books %}
<li><a href="{% url 'detail' book.pk %}">{{ book.title }}</a> by {{ book.author }}</li>
{% endfor %}
</ul>
</body>
</html>
The myapp/templates/home.html file
  1. Create a new file named detail.html in the templates folder and add the following code. This HTML code creates a detailed view page for a specific book, displaying its title, author, publication date, and description. The title of the book is dynamically inserted into the page’s <title> tag and <h1> header. Additionally, there is a link that allows users to navigate back to the main book list page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ book.title }}</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #2c3e50;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
}
a {
text-decoration: none;
color: #3498db;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>{{ book.title }}</h1>
<p><strong>Author:</strong> {{ book.author }}</p>
<p><strong>Publication Date:</strong> {{ book.publication_date }}</p>
<p><strong>Description:</strong> {{ book.description }}</p>
<a href="{% url 'home' %}">Back to List</a>
</body>
</html>
The myapp/templates/detail.html file
  1. Create a new file named create.html in the templates folder and add the following code. This HTML code creates a form for adding a new book to the application. It displays the heading "Add a New Book" and includes a form that uses the POST method to send the form data to the server. The {% csrf_token %} tag is used for security, protecting the form from cross-site request forgery (CSRF) attacks. The form fields are rendered using {{ form.as_p }}, which automatically displays each form field as a paragraph. There is a "Save" button to submit the form and a "Cancel" link that redirects the user back to the home page, where they can see the list of books.

<!DOCTYPE html>
<html>
<head>
<title>Add Book</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #2c3e50;
}
a {
text-decoration: none;
color: #3498db;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Add a New Book</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
<a href="{% url 'home' %}">Cancel</a>
</body>
</html>
The myapp/templates/create.html file

Step 8: Test the book detail view

To test the detail view, you can run the following commands to create a few books.

  1. Open the Django shell using the following command:

python manage.py shell
  1. Run the following to the Django shell to create a couple of books.

from myapp.models import Book
Book.objects.create(title="Book 1", author="Author 1", publication_date="2024-01-01", description="Description of Book 1")
Book.objects.create(title="Book 2", author="Author 2", publication_date="2024-02-01", description="Description of Book 2")

Step 9: Run the application

Run the following playground to start the application, and click on the URL underneath the Run button to see it in action.

from django.test import TestCase
from myapp.models import Book

Book.objects.create(
    title="The Catcher in the Rye",
    author="J.D. Salinger",
    publication_date="1951-07-16",
    description="A story about a young man navigating life in post-war America.",
)
Book.objects.create(
    title="Brave New World",
    author="Aldous Huxley",
    publication_date="1932-08-30",
    description="A dystopian society in the future where technology controls people's lives.",
)
Book.objects.create(
    title="Emma",
    author="Jane Austen",
    publication_date="1815-12-23",
    description="A story about a young woman who attempts to play matchmaker among her friends, with unforeseen consequences.",
)

Knowledge test

Let’s attempt a short quiz to assess our understanding.

Q

In the URL pattern path('book/<int:pk>/', ...), what does <int:pk> capture?

A)

The ID of the book

B)

The name of the book

C)

The author of the book

D)

The description of the book

Build Your Own Mental Health Counseling Chatbot with Django and OpenAI!

Ready to create a powerful mental health chatbot? In this project, you’ll learn how to combine Python, HTML/CSS, JavaScript, Django, and the OpenAI API to build a supportive mental health counseling tool. Start coding today and make a difference with technology!

Conclusion

In this Answer, we learned how to create a function-based detail view in Django. By retrieving a single object and rendering it with a template, you can display detailed information about any model instance in your application. This approach provides both flexibility and simplicity, allowing you to create dynamic, data-driven web pages efficiently.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is function-based detail view in Django?

A function-based detail view in Django is a view written using a Python function to retrieve and display detailed information of a specific database record (like a model instance) based on the URL parameters. It allows for more explicit control over the logic and rendering compared to class-based views.


What are detail views in Django?

Detail views in Django are views that display detailed information about a single instance of a model. Typically, a detail view fetches an object using a unique identifier (like the primary key) passed in the URL and then displays its properties in a structured manner. Django offers both function-based and class-based approaches for creating detail views.


What is class-based view and function-based view in Django?

  • A function-based view (FBV) is a traditional view in Django where we define a function to handle the HTTP request and return a response. It is straightforward and allows developers to have full control over the logic of the view.
  • A class-based view (CBV) is a more abstract and reusable approach, where views are defined as Python classes with predefined methods that handle common tasks (like displaying a model’s details). CBVs offer more flexibility and can be customized by extending base views.

What are the different types of views in Django?

Django offers several types of views to handle different use cases:

  • Function-Based Views (FBVs): Simple and explicit views defined by functions.
  • Class-Based Views (CBVs): Views defined by classes that provide reusable methods for handling common tasks.
  • Generic Views: A set of pre-built views in Django (such as DetailView and ListView) that simplify the implementation of common patterns.
  • Template Views: Views that render templates without processing much logic.

Free Resources