Template for Detail Page
An HTML template for the Detail page is more straightforward. You don't need to use the for
statement to display multiple objects. The URL dispatcher has already processed a complex part of the detail page. On the detail page, you need to show an object for the specified record requested by the URL dispatcher.
How is a detail page displayed?
A brief understanding of the entire process, from an HTTP request to an HTTP response for a detail page, may help you understand how the detail page template works. The following steps are brief explanations of the processes from an HTTP request to an HTTP response. There are more detailed steps in between, but this may be enough to roughly understand the detail page template.
- An HTTP request is generated by a browser. For example, a URL ends with .../detail/3/. The last part indicates that the browser is requesting a record object with
id=3
.pk
as a primary key. The primary key is set in theid
field. - URL Dispatcher (urls.py) dispatches the request to DetailView.
- DetailView calls the third record object (
id=3
) through models.py. - The '
object
' part in detail.html is replaced with the record object. - DetailView returns an HTML document with requested data (record object
id=3
).
Practice
Objective:
Create a template for the detail page
In this practice, we'll create a simple detail page template by implementing the uppercase
filter and the get_FOO_display
method.
1. Edit course_detail.html
Open the course_detail.html file, add the yellow lines below, and save the file.
<h1>DETAIL Page</h1>
<p>Course Title : {{ object.title|upper }} </p>
<p>Level : {{ object.get_level_display }}</p>
2. Check the result in a browser
After saving the file, Go to localhost:8000/employee-learning/course-detail/3/. You can change the number at the end. As long as there is data, you'll see a page like the one below.
3. Check the user-friendly name for the object
Like you did for the list page, you can use a user-friendly name for object
.
In CourseDetail, we set context_object_name = 'course_object'
. Check if it works by updating the code with the yellow parts below.
:
<p>Course Title : {{ course_object.title|upper }} </p>
<p>Level : {{ course_object.get_level_display }}</p>
Go to localhost:8000/employee-learning/course-detail/3/. You can confirm that the browser still shows the same results.
For the DetailView in the Django official documentation, check this link Django documentation reference: DetailView