Exercise - Implement generic views to display data
We want to create a new detail page for dogs. We're going to use the generic view DetailView
to streamline the amount of code we need to create.
Important
This exercise assumes that you've completed the setup steps earlier in this module.
Create DogDetail view
We start by creating the detail view class.
Inside Visual Studio Code, open dog_shelters/views.py.
Underneath the line that reads
# TODO: Import generic views
, add the following code to import the generic views module.# TODO: Import generic views from django.views import generic
Add the following code to the bottom of views.py to create the generic view for
DogDetail
and set the model, template, and context object.class DogDetailView(generic.DetailView): model = models.Dog template_name = 'dog_detail.html' context_object_name = 'dog'
Register the detail view
With the view created, we can register the path.
Open dog_shelters/urls.py.
Underneath the line that reads
# TODO: Register detail view
, add the following code to register the path for ourDogDetailView
.# TODO: Register detail view path('dog/<int:pk>', views.DogDetailView.as_view(), name='dog_detail'),
Important
Remember the trailing comma at the end of the line.
Create the HTML template
Now you'll create the HTML template to display out the details of the dog. The object name will be dog
as we set that when creating the form.
Inside Visual Studio Code, create a new file inside dog_shelters/templates named dog_detail.html.
Add the following code to dog_detail.html to create the template to display the details for the dog.
{% extends 'base.html' %} {% block title %} {{ dog.name }} {% endblock %} {% block content %} <h2>{{ dog.name }}</h2> <div>About {{ dog.name }} - {{ dog.description }}</div> {% endblock %}
Update the shelter detail page to include our link
With our path registered and template created, we can update the shelter detail template to include links to our dog detail page.
Open dog_shelters/templates/shelter_detail.html.
Underneath the line that reads
{# TODO: Add link to dogs #}
, add the following code to create a link for each dog to the detail view.{# TODO: Add link to dogs #} <a href="{% url 'dog_detail' dog.id %}"> {{dog.name}} </a>
Test your page
With everything created, let's see our page in action.
Save all the files by selecting File > Save All.
In your browser, go to
http://localhost:8000
.From the list of shelters, select Contoso.
From the list of dogs, select Roscoe.
The details page appears.
We've now created a view by using the generic view system in Django!