Last modified: Jan 10, 2023 By Alexander Williams
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.
models.py
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)
views.py
In our views, we need to add the following code.
#views.py
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.
urls.py
now we need to add a path for our UsersDetail view.
#url.py
path('<slug:slug>/', UsersDetail.as_view()), #slug = slug field
test.html
Now, we need to create test.html in TEMPLATES folder and place the following code in it.
#test.html
<!DOCTYPE html>
<html>
<head>
<title>Detailview</title>
</head>
<body>
<h1>hello {{object.firstname}} !</h1>
</body>
</html>
let's add some records to our model

result:

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