6.4-5 form
基于类来做有很多好处 比如可以定义很多函数
- users的views.py中继承View
<code>from django.views.generic.base import View
class LoginView(View):
def get(self,request):
return render(request, "login.html", {})
def post(self,request):
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", {"msg":"用户名或密码错误!"})
</code>
调用两个方法get post是View自动完成的
- urls.py
<code>
from users.views import LoginView
url('^login/$',LoginView.as_view(),name="login")
</code>
代替了user_login方法 可将user_login删除或注释
是基于View类完成的
调用as_view方法时要加()
django的form
- 在users app中新建forms.py
<code>
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True,min_length=5)
</code>
forms.CharField里还有很多功能
- 在views。py的LoginView类中的post函数中
<code>from .forms import LoginForm
def post(self,request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
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", {"msg": "用户名或密码错误!"})
else:
return render(request, "login.html", {"login_form":login_form}) <code>
在post方法中传入POST方法 这个View已经验证每个字段是否合法
调用is_valid方法完成每个字段是否合法的工作 如果合法取出用户密码做authenticate认证 判断authenticate认证返回是不是user 如果user不为空 调用login完成整个登陆跳转到index 如果valid失败把form返回 这样就可以取到form里的的错误信息