Detail View – Class Based Views Django
Detail View refers to a view (logic) to display one instances of a table in the database.Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views with few lines only.
After you have a project and an app, let’s create a model of which we will be creating instances through our view.
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField(blank=True, default="")
slug = models.SlugField(max_length=200)
published = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-published',)
def __str__(self):
return self.title
Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create DetailView for, then Class based DetailView will automatically try to find a template in app_name/modelname_detail.html or you can use template_name.
class ArticleDetail(DetailView):
model = Article
#if template_name is specified, then it will look like the below mentioned code.
# template_name = 'blogpost/article_detail.html'
Now create a url path to map the view.
path('slug>', views.ArticleDetail.as_view(), name='articledetail'),
slug should be in between angular brackets.
Manipulate Context Data in DetailView
By default DetailView will only display fields of a table. If one wants to modify this context data before sending it to template or add some extra field, context data can be overridden.
class ArticleDetail(DetailView):
model = Article
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
# add extra field
context["latest"] = Article.objects.all()
return context
Now the template will change to
{{ object.title }}
{{ object.body }}
{% for latest_blog in latest %}
a href="{% url 'articledetail' latest_blog.slug %}">{{latest_blog.title|safe}}
{% endfor %}