Understanding Django DetailView With Simple Example

Understanding Django DetailView With Simple Example

In this tutorial, we'll learn how to use DetailView with a simple example.

1. What is DetailView?

Django DetailView allows us to display information from a registration model.
To understand, let's do an example.

2. Django DetailView example

in this example, we'll display detail of records dynamically.


Let's create a simple model that we want to make a page for each record dynamically.

# models.py
class Users(models.Model):
    firstname = models.CharField(max_length=300)
    last_name = models.CharField(max_length=300)


In our views, we need to add the following code.

from django.views.generic import DetailView

class UsersDetail(DetailView):
    model = Users # model
    template_name = 'test.html' # template's path
    slug_field = 'firstname' # slug field

model : Your Model.
template_name : Template's name.
slug_field : Model's field that you want to use as URL.


now we need to add a path for our UsersDetail view.

path('<slug:slug>/', UsersDetail.as_view()), #slug = slug field


Now, we need to create test.html in TEMPLATES folder and place the following code in it.

<!DOCTYPE html>
<h1>hello {{object.firstname}} !</h1>

let's add some records to our model


As you can see, we have a dynamic URL that shows information for each model's record.