详细视图–基于函数的视图|Django

2021年3月31日16:08:02 发表评论 737 次浏览

详细视图指的是一个视图(逻辑),用于显示数据库中表的特定实例以及所有必要的详细信息。它用于在单个页面或视图中显示多种类型的数据,例如,用户的概要文件。Django提供了对细节视图的特别支持,但是让我们来看看它是如何通过基于函数的视图手工完成的。本文围绕着细节视图展开,它涉及到Django表单、Django模型等概念。

对于Detail View, 我们需要一个带有一些模型和多个实例的项目, 这些项目将被显示。

Django详细视图–基于函数的视图

使用示例说明如何创建和使用详细视图。考虑一个名为lsbin的项目,它有一个名为geeks的应用程序

请参阅以下文章, 以检查如何在Django中创建项目和应用。
如何在Django中使用MVT创建基本项目?
如何在Django中创建应用程序?

在拥有一个项目和一个应用程序之后, 让我们创建一个模型, 我们将通过我们的视图创建该模型。在geeks/models.py,

# import the standard Django Model
# from built-in library
from django.db import models
   
# declare a new model with a name "GeeksModel"
class GeeksModel(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 ):
         return self .title

创建此模型后, 我们需要运行两个命令以便为同一数据库创建数据库。

Python manage.py makemigrations
Python manage.py migrate

现在, 让我们使用Shell创建该模型的一些实例, 运行表格bash,

Python manage.py shell

输入以下命令

>>> 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="title3", description="description3").save()

现在, 我们已经为后端做好了一切准备。验证是否已从创建实例http://localhost:8000/admin/geeks/geeksmodel /

django-Detailview-check-models-instances

对于详细视图人们将需要一些识别才能获得模型的特定实例。通常它是唯一的主键, 例如id。要指定此标识, 我们需要在urls.py中定义它。去怪胎/ urls.py,

from django.urls import path
  
# importing views from views..py
from .views import detail_view
  
urlpatterns = [
     path( '<id>' , detail_view ), ]

让我们为其创建一个视图和模板。在geeks / views.py,

from django.shortcuts import render
  
# relative import of forms
from .models import GeeksModel
  
# pass id attribute from urls
def detail_view(request, id ):
     # dictionary for initial data with 
     # field names as keys
     context = {}
  
     # add the dictionary during initialization
     context[ "data" ] = GeeksModel.objects.get( id = id )
          
     return render(request, "detail_view.html" , context)

在中创建模板templates / Detail_view.html,

< div class = "main" >
      
     <!-- Specify fields to be displayed -->
     {{ data.title }}< br />
     {{ data.description }}< br />
  
</ div >

让我们检查一下

http://本地主机:8000/1

django-detail-view-demo1

详细视图工作正常。还可以根据多种形式中需要的使用类型显示选定的字段。通常用来定义详细视图的不是id,而是slug。要了解更多关于slug和SlugField的信息,请访问-在Django模型中添加slug字段

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: