流程为:
urls.py----->app/urls.py------>app/views.py------->template/index.html



基于类的view视图
一开始django只有基于函数的视图(function-based view),为了解决开发视图中繁琐的重复代码,基于类的view视图出现了
于是你可以再你的view中去引用view


View自带了很多的方法,其中包括get,post等。
像之前我们写一个表单请求,代码与下面的类似
#不基于类
def login_te(request):
if request.method =="POST":
user_name = request.POST.get("username","")
pass_word = request.POST.get("password","")
user = authenticate(username=user_name,password=pass_word)
if user is not None:
login(request,user)
return render(request,'index.html')
else:
return render(request,'login.html',{'message':"账号密码错误"})
elif request.method=="GET":
return render(request,'login.html',{})
我们需要去调用request.method 并检查他是post请求还是get请求,并且分别对他们进行数据的整理以及结果的处理。
但是如果我们使用了类视图
这里的get直接可以获取username和password,基于类的话他可以自定定义时post请求还是get请求
class Login_View(View):
def post(self,request):
form = loginForm(request.POST) #传进来一个字典的参数
if form.is_valid(): #判断是否符合form表单要求
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return render(request, 'index.html')
else:
return render(request,'login.html',{'message':'账号未激活'})
else:
return render(request,'login.html',{'message':'账号密码错误'})
else:
return render(request, 'login.html', {'form_message':form})
def get(self,request):
return render(request,'login.html')
直接使用 post和get方法就可以
不同的View
在django.views.generic中我们可以看见有很多的类

但是他们都继承至view这个父类。同时还继承了一些mixin功能类。
如TemplateView继承了TemplateResponseMixin,ContextMixin,View


这里可以写入template_name的名字。
经过一系列的转换最终会跳转至template_name所指向的html页面

所以之前的跳转,我们可以写成这样。
网友评论