Django中可以使用views进行管理,类似于WPF的MVVM的ViewModel层,也相当于MVC架构的模Controller层。
一、基于函数的视图FBV(Function-Based View)
通过定义一个函数,包含HttpRequest对象作为参数,用来接受客户端请求,然后返回HttpResponse对象做为响应放回给客户端。
1.1 先定义一个模板文件
在template中定义一个模板文件persondetail.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Person Details</title>
</head>
<body>{{ Person }}{{ Person.name }}{{ Person.phone }}
</body>
</html>
1.2 在views.py中创建一个函数person_detail
def person_detail(request: HttpRequest, pk: int):"""Show person detailpk: 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})
1.3 在urls.py中添加新的url
from django.urls import path, re_path
from serverapp import views as serverapp_viewsurlpatterns = [path('test/2023', serverapp_views.test), # 精确匹配path('converter/<int:num>', serverapp_views.converter), # 格式转换re_path(r'^re/(?P<num>[0-9]{1,4})/$', serverapp_views.rematch), # 正则表达式,通过添加起止符限制匹配,避免中间多级路径后匹配到,造成错误匹配。path('person', serverapp_views.get_person), # 获取人员信息path('personform', serverapp_views.get_personform), # 使用表单获取人员信息path('person_detail/<int:pk>', serverapp_views.person_detail) # 视图演示,展示人员信息
]
1.4 运行软件,在客户端访问
二、基于类的视图CBV(Class-Based View)
基于类的视图与基于函数的视图大同小异,只不过是使用类代替函数。
2.1 再views.py文件中定义类
class PersonDetailView(View):"""人员信息视图类"""form_class = PersonForm # 定义表单类initial = {"key":"value"} # 定义表单初始值tamplate_name = "personform.html" # templage file namedef 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 dataname = 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})
2.2 注册新的url
from django.urls import path, re_path
from serverapp import views as serverapp_viewsurlpatterns = [path('test/2023', serverapp_views.test), # 精确匹配path('converter/<int:num>', serverapp_views.converter), # 格式转换re_path(r'^re/(?P<num>[0-9]{1,4})/$', serverapp_views.rematch), # 正则表达式,通过添加起止符限制匹配,避免中间多级路径后匹配到,造成错误匹配。path('person', serverapp_views.get_person), # 获取人员信息path('personform', serverapp_views.get_personform), # 使用表单获取人员信息path('person_detail/<int:pk>', serverapp_views.person_detail) , # 视图演示,展示人员信息path('personformview', serverapp_views.PersonDetailView.as_view()) # 基于类的视图
]
2.3 定义html文件
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>User Name</title>
</head>
<body><!--action 是访问的url--><form action="/serverapp/personformview" method="post">{% csrf_token %} <!--防止跨域攻击-->{{ personform }} <!--引用表单,views函数中定义的名称一致--><button type="submit">提交</button></form>
</body>
</html>