DetailView - представления на основе классов Django
Подробное представление относится к представлению (логике) для отображения одного экземпляра таблицы в базе данных. Мы уже обсудили основы подробного представления в подробном представлении - представления на основе функций Django. Представления на основе классов предоставляют альтернативный способ реализации представлений как объектов Python вместо функций. Они не заменяют функциональные представления, но имеют определенные отличия и преимущества по сравнению с функциональными представлениями:
- Организация кода, связанного с конкретными методами HTTP (GET, POST и т. Д.), Может быть решена отдельными методами вместо условного перехода.
- Объектно-ориентированные методы, такие как миксины (множественное наследование), могут использоваться для разделения кода на повторно используемые компоненты.
Представлениями на основе классов проще и эффективнее управлять, чем представлениями на основе функций. Представление на основе функций с множеством строк кода может быть преобразовано в представления на основе классов всего несколькими строками. Именно здесь вступает в силу объектно-ориентированное программирование.
Django DetailView - представления на основе классов
Illustration of How to create and use Detail view using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
- How to Create a Basic Project using MVT in Django?
- How to Create an App in Django ?
After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,
| # import the standard Django Model# from built-in libraryfromdjango.db importmodels  # declare a new model with a name "GeeksModel"classGeeksModel(models.Model):     # fields of the model    title =models.CharField(max_length =200)    description =models.TextField()     # renames the instances of the model    # with their title name    def__str__(self):        returnself.title | 
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations Python manage.py migrate
Now let’s create some instances of this model using shell, run form bash,
Python manage.py shell
Enter following commands
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
                       title="title1",
                       description="description1").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()
Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/

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. In our case it is geeks/templates/geeks/geeksmodel_detail.html. Let’s create our class based view. In geeks/views.py,
| fromdjango.views.generic.detail importDetailView from.models importGeeksModel classGeeksDetailView(DetailView):    # specify the model to use    model =GeeksModel | 
Now create a url path to map the view. In geeks/urls.py,
| fromdjango.urls importpath # importing views from views..pyfrom.views importGeeksDetailViewurlpatterns =[    # <pk> is identification for id field,    # slug can also be used    path("<pk>/", GeeksDetailView.as_view()),] | 
Create a template in templates/geeks/geeksmodel_detail.html,
| <h1>{{ object.title }}</h1><p>{{ object.description }}</p> | 
Let’s check what is there on http://localhost:8000/1/
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 overriden.
In geeks/views.py,
| fromdjango.views.generic.detail importDetailView from.models importGeeksModel classGeeksDetailView(DetailView):    # specify the model to use    model =GeeksModel     # override context data    defget_context_data(self, *args, **kwargs):        context =super(GeeksDetailView,             self).get_context_data(*args, **kwargs)        # add extra field         context["category"] ="MISC"        returncontext | 
In geeks/templates/geeksmodel_detail.html,
| <h1>{{ object.title }}</h1><p>{{ object.description }}</p><p>{{ category }}</p> | 
Now check, if the category is added.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course