Django中可以使用views进行管理,类似于WPF的MVVM的ViewModel层,也相当于MVC架构的模Controller层。
通过定义一个函数,包含HttpRequest对象作为参数,用来接受客户端请求,然后返回HttpResponse对象做为响应放回给客户端。
在template中定义一个模板文件persondetail.html
Person Details
{{ Person }}
{{ Person.name }}
{{ Person.phone }}
def person_detail(request: HttpRequest, pk: int):
"""
Show person detail
pk: the primarykey of person.
"""
try:
p = Person.objects.get(pk=pk)
except Person.DoesNotExist:
raise Http404("Person Does Not Exist.")
return render(request, "persondetail.html", {"Person": p})
from django.urls import path, re_path
from serverapp import views as serverapp_views
urlpatterns = [
path('test/2023', serverapp_views.test), # 精确匹配
path('converter/', serverapp_views.converter), # 格式转换
re_path(r'^re/(?P[0-9]{1,4})/$', serverapp_views.rematch), # 正则表达式,通过添加起止符限制匹配,避免中间多级路径后匹配到,造成错误匹配。
path('person', serverapp_views.get_person), # 获取人员信息
path('personform', serverapp_views.get_personform), # 使用表单获取人员信息
path('person_detail/', serverapp_views.person_detail) # 视图演示,展示人员信息
]
基于类的视图与基于函数的视图大同小异,只不过是使用类代替函数。
class PersonDetailView(View):
"""人员信息视图类"""
form_class = PersonForm # 定义表单类
initial = {"key":"value"} # 定义表单初始值
tamplate_name = "personform.html" # templage file name
def get(self, request: HttpRequest, *args, **kwargs):
"""Get method"""
# 渲染表单
return render(request, self.tamplate_name, {"personform": self.form_class(initial= self.initial)})
def post(self, request: HttpRequest, *args, **kwargs):
"""POST method"""
form = self.form_class(request.POST)
if form.is_valid():
# get data
name = form.cleaned_data['name']
phone = form.cleaned_data['phone']
return HttpResponse(f"The peson name is {name}, phone is {phone}")
return render(request, self.tamplate_name, {"personform": form})
from django.urls import path, re_path
from serverapp import views as serverapp_views
urlpatterns = [
path('test/2023', serverapp_views.test), # 精确匹配
path('converter/', serverapp_views.converter), # 格式转换
re_path(r'^re/(?P[0-9]{1,4})/$', serverapp_views.rematch), # 正则表达式,通过添加起止符限制匹配,避免中间多级路径后匹配到,造成错误匹配。
path('person', serverapp_views.get_person), # 获取人员信息
path('personform', serverapp_views.get_personform), # 使用表单获取人员信息
path('person_detail/', serverapp_views.person_detail) , # 视图演示,展示人员信息
path('personformview', serverapp_views.PersonDetailView.as_view()) # 基于类的视图
]
User Name