强力Django第六章4-完善用户登录增加form验证

python推荐基于类的方法完成登录
修改配置如下:

1.增加form组件对用户提交的表单进行预处理,验证参数是否正确,这样在调用数据库之前就已经过滤掉相应的错误信息了。

在(app)users 中创建新文件forms.py

# _*_ encoding:utf-8 _*_
__author__ = 'luky'
__date__ = '2018/4/23 10:44'

from django import forms


class LoginForm(forms.Form):
    username = forms.CharField(required=True)
    password = forms.CharField(required=True, min_length=5) #设置必填,最小长度5,不符合不去查数据库。

2.更新views.py配置

# _*_ encoding:utf-8 _*_
__author__ = 'luky'
__date__ = '2018/4/12 15:46'

from django.shortcuts import render
from django.contrib.auth import authenticate, login

#1自定义登陆的字段,用户名或者email都行
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
#1自定义登陆的字段,用户名或者email都行
from django.views.generic.base import View

# Create your views here.
from .models import UserProfile
from.forms import LoginForm


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):
    def get(self, request):
        return render(request, "login.html", {})
    def post(self, request):
        login_form = LoginForm(request.POST)
        #调用form方法,验证用户输入
        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:
            #2{"msg":"用户名密码输入错误!"}定义报错输。在login.html代码中加入
            return render(request, "login.html", {"msg":"用户名密码输入错误!"})

3.更新urls.py配置

from django.conf.urls import url
# from django.contrib import admin
from django.views.generic import TemplateView
import xadmin

from users.views import LoginView

urlpatterns = [
    url(r'^xadmin/', xadmin.site.urls),
    url('^$', TemplateView.as_view(template_name="index.html"), name="index"),
    url('^login/$', LoginView.as_view(), name="login")
]

4.验证
设置断点 后启动DEBUG


image.png

输入用户密码,密码123 小于5位长度


image.png

然后查看pycharm 按F8后在debug中会看到errors信息证明验证功能实现。
image.png

你可能感兴趣的:(强力Django第六章4-完善用户登录增加form验证)