django-Form 表单验证初探之优化


发布时间:2019-02-15 13:08    作者: Uncle Hui   已过去:1 年,3 月   阅读总量:166 已被赞:0


前篇的用户登陆验证,可以不在视图里验证,直接在表单里验证也是一样的,写法基本一样,例如:

表单:

from django import forms
from django.contrib import auth
class LoginFrom(forms.Form):
    username = forms.CharField(label='用户名',widget=forms.TextInput(attrs={"class":"form-control",'placeholder':'请输入用户名'}))
                                             # widget=forms.TextInput 样式
    password = forms.CharField(label='密码',widget=forms.PasswordInput(attrs={"class":"form-control",'placeholder':'请输入密码'}))
    #attrs=可以传递一些参数进去,比如CSS类
    def clean(self):#调用这个内置方法:
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']

        user = auth.authenticate( username=username, password=password)  # 去用户模型里比对
        if user is  None:  # 如果查不到,就会返回一个空值
            raise forms.ValidationError('用户名或密码错误')
        else: #验证如果通过,就把用户写进去
            self.cleaned_data['user'] = user
        return self.cleaned_data

视图修改:

def login(request):
    if request.method == 'POST': #如走POST请求
        login_form = LoginFrom(request.POST) #绑定验证表单,并将POST内容提交去验证
        if login_form.is_valid(): #如果验证通过
            user = login_form.cleaned_data['user'] #把表单验证好的user取出来
            auth.login(request,user)  #  就让这个用户登陆
            # return render(request.GET.get('from',reverse('cjcx2018_index')))
            return redirect(reverse('cjcx2018_index'))
                #跳转回来登陆的页面,如果未传入from=就回首页(每个登陆链接处:
            # <a href="{% url 'blog_login' %}?from={{ request.get_full_path }}">还没有账号?点此注册</a>
    else:
        login_form = LoginFrom() # 绑定验证表单
    context={
            'login_form':login_form
        }
    return render(request,'cjcx2018/cjcx2018_login.html',context)

 

HTML 模板:把内容遍历出来,方便指定错误信息显示的位置,也可以不遍历出来,直接一个{{login_form}}

<form action="{% url 'cjcx2018_login' %}" method="post">
{% csrf_token %}
{% for field in login_form %}
    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
    {{ field }}
    <p>{{ field.errors.as_text }}</p>
{% endfor %}
<span>{{ login_form.non_field_errors }}</span>
    <input type="submit" value="登陆">
</form>

点赞

0




登陆后方可评论