FBV:function base views (views中使用函数来接收路由)
CBV:class base views(views中使用class来接收路由)
前几篇文章中都是使用的FBV,下面使用CBV处理路由请求
views.py部分代码
from django.views import View #导入View模块
class Cbv(View): #定义Cbv类继承自View
def get(self,request): #接收get请求
return render(request,"index.html")
def post(self,request): #接收post请求
user = request.POST.get("user", False)
password = request.POST.get("pwd", False)
users_list = models.UserInfo.objects.all()
if not user or not password:
return render(request, "index.html", {"isnot":'yes'})
for item in users_list:
if user == item.username and password == item.password:
return redirect("/page/")
return render(request, "index.html", {"isexists":"false"})
urls.py部分代码
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^page/', views.page),
url(r'^index/', views.Cbv.as_view()), #Cbv是views中的定义的继承自View的类,as_view()是固定写法
]
index.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/index/" method="post">
用户名:<input type="text" name="user">
密码:<input type="password" name="pwd">
<input type="submit" value="登录">
{% if isnot == "yes" %}
<p>用户名或密码不能为空!</p>
{% endif %}
{% if isexists == "false" %}
<p>用户名或密码错误,请重新输入!</p>
{% endif %}
</form>
</body>
</html>
序列化
在views中,有些场景需要使用HttpResponse来返回数据,如果返回的数据是dic类型,可以使用json.dumps()方法把dic类型转换为string类型,通过HttpResponse返回
import json
def test(request):
dic = {"data":"test data","user":"zhangsan"}
return HttpResponse(json.dumps(dic)) #使用json.dumps()方法把dic类型转换为string类型
如果返回的是数据库查询的QuerySet或者QuerySetList类型数据,直接使用json.dumps()方法转换就会报错。这时就要使用序列化serializers
from django.core import serializers #导入serializers模块
def test(request):
dic = {"data":"test data","user":"zhangsan"}
user_obj = models.UserInfo.objects.filter(name="张三")
user_json = serializers.serialize("json",user_obj) #把queryset序列化为json
dic["data"] = user_json
return HttpResponse(json.dumps(dic))