django Form 表单 总结与小实例

开头寄语:

这几天一直在看Django的form表单验证,然后想对于这几天要有个总结。

  • 首先,先来看一下找到的一个form表单验证的流程:

验证过程


流程详解
1. 函数full_clean()依次调用每个field的clean()函数,该函数针对field的max_length,unique等约束进行验证,如果验证成功则返回值,否则抛出ValidationError错误。如果有值返回,则放入form的cleaned_data字典中。
2. 如果每个field的内置clean()函数没有抛出ValidationError错误,则调用以clean_开头,以field名字结尾的自定义field验证函数。验证成功和失败的处理方式同步骤1。
3. 最后,调用form的clean()函数——注意,这里是form的clean(),而不是field的clean()——如果clean没有错误,那么它将返回cleaned_data字典。
4. 如果到这一步没有ValidationError抛出,那么cleaned_data字典就填满了有效数据。否则cleaned_data不存在,form的另外一个字典errors填上验证错误。在template中,每个field获取自己错误的方式是:{{ form.username.errors }}。
5. 最后,如果有错误is_valid()返回False,否则返回True。
注意一点:自定义验证机制时:clean()和clean_<field>&()的最后必须返回验证完毕或修改后的值.

  • 补充小插曲

我们在写表单类的时候 一般也继承froms.Form,但是也见过继承ModleForm,应该来说继承那个都可以,个人认为继承ModleForm时,主要是再写表单类的时候方便些,比如通过如下方式写表单类

from app01.models import Moment
from django import forms
from django.forms import ModelForm


class MomentForm(ModelForm):

    class Meta:
        model = Moment      # Models类名称
        fields = "__all__"  # 导入所有的字段
        # fields = ['content', 'user_name']

 

 

 

  • 下面是自己写的一个小实例,内容包括 form表单验证与session

需求如下:

用户访问首页,在首页点击注册,对注册表单进行验证,登录成功后进入后台管理界面

表单类:

表单中包含input标签 select标签 checkbox标签 也定义了一些自定义的验证逻辑,这里也看了一些资料,我认为在定义clean_xx 函数时 最后要return 验证字段的值,而重写clean()方法时,最后要return clean_data。

# 注册页面手机号验证
def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    value = str(value)
    if not mobile_re.match(value):
        raise forms.ValidationError('手机号码格式错误')




class RegisterForm(forms.Form):
    username = forms.CharField(
        error_messages={'required': '用户名不能为空', 'min_length': '最小长度为4', 'max_length': '最大长度为30'},
        max_length=30,
        min_length=4,
    )

    password = forms.CharField(
        error_messages={'required': '密码不能为空'}
    )

    password_again = forms.CharField(
        error_messages={'required': '密码不能为空',}
    )
    email = forms.EmailField(
        required=False,
        error_messages={'invalid': '邮箱格式错误'}
    )
    phone = forms.IntegerField(validators=[mobile_validate],
                               error_messages={'required': '手机号不能为空', 'invalid': '必须输入数字'}
                               )
    roles = Role.objects.all().values_list('id', 'role_name')
    role = forms.CharField(
        error_messages={'required': '角色不能为空'},
        widget=forms.widgets.Select(choices=roles, attrs={'class': 'c1'}))
    marry_choice = (
        ('0', ''),
        ('1', ''),
        ('2', '已婚'),
        ('3', '未婚'),
    )
    marry = forms.MultipleChoiceField(
        error_messages={'required': '选择不能为空'},
        choices=marry_choice, widget=forms.CheckboxSelectMultiple())

    favors = Favor.objects.all().values_list('id', 'favor_name')
    favor = forms.CharField(
        error_messages={'required': '爱好不能为空'},
        widget=forms.widgets.Select(choices=favors, attrs={'class': 'c1', 'multiple': 'multiple'}))
    code = forms.CharField(
        error_messages={'required': '验证码不能为空'}
    )

    # 自定义验证  验证password
    def clean_password(self):
        cleaned_data = super(RegisterForm, self).clean()
        user_data = cleaned_data.get('password')
        if user_data == 'XXX':
            raise forms.ValidationError(u'密码太简单了')
        return user_data

    # 验证两次输入的密码是否一致
    def clean_password_again(self):
        password = self.cleaned_data['password']
        password_again = self.cleaned_data['password_again']
        if password != password_again:
            raise forms.ValidationError('两次密码不一致')
        return password_again

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['role'] = forms.CharField(
            widget=forms.widgets.Select(choices=Role.objects.all().values_list('id', 'role_name'), attrs={'class': 'c1'})
        )
        self.fields['favor'] = forms.CharField(
            widget=forms.widgets.Select(choices=Favor.objects.all().values_list('id', 'favor_name'),
                                        attrs={'class': 'c1'})
        )



    # 验证选择婚姻是否正确
    def clean_marry(self):
        data_list = self.cleaned_data['marry']
        if len(data_list) == 2:
            if '0' and '1' in data_list:
                raise forms.ValidationError('男女选择有误!')
            elif '2' and '3' in data_list:
                raise forms.ValidationError('婚姻选择有误!')
            else:
                return data_list
        else:
            raise forms.ValidationError('请选择男女和婚姻!')

前段html

这里面 input标签 包括自己写的 也有 通过Django自动生成的。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>用户注册</title>
        <link rel="stylesheet" type="text/css" href="/statics/css/one.css">
    </head>
    <body>
        <div class="register-page">
            <div class="mid-css">
                <form method="post" action="/register/">
                     <div class="commons-css">
                         <span class="register-span">用户名:</span>
                         <input type="text" name="username" placeholder="请输入用户名">
                         <span class="error-info">{{ errors.username.0 }}</span>
                    </div>

                     <div class="commons-css">
                         <span class="register-span">密码:</span>
                         <input type="text" name="password" placeholder="请输入密码">
                          <span class="error-info">{{ errors.password.0 }}</span>
                    </div>

                     <div class="commons-css">
                         <span class="register-span">确认密码:</span>
                         <input type="text" name="password_again" placeholder="请输入密码">
                          <span class="error-info">{{ errors.password_again.0 }}</span>
                    </div>

                     <div class="commons-css">
                         <span class="register-span">邮箱:</span>
                         <input type="text" name="email" placeholder="请输入邮箱">
                          <span class="error-info">{{ errors.email.0 }}</span>
                    </div>

                     <div class="commons-css">
                         <span class="register-span">手机号:</span>
                         <input type="text" name="phone" placeholder="请输入手机号">
                          <span class="error-info">{{ errors.phone.0 }}</span>
                    </div>

                     <div class="commons-css">
                         <span class="register-span">角色:</span>
                         {{ form.role }}
                          <span class="error-info">{{ errors.role.0 }}</span>
                    </div>

                    <div class="favor-css ClearFloat">
                         <span class="favor-span">婚姻状况:</span>
                         {{ form.marry }}
                          <span class="error-info">{{ errors.marry.0 }}</span>
                    </div>


                     <div class="commons-css">
                         <span class="register-span">爱好:</span>
                         {{ form.favor }}
                          <span class="error-info">{{ errors.favor.0 }}</span>
                    </div>




                    <div class="commons-css">
                        <span class="register-span">验证码:</span>
                        <input type="text" name="code" style="width: 150px">
                        <span class="span-code" onclick= "GetCode(this)" id="span">点击获取</span>
                        {% if errors.code.0 %}
                            <span class="error-info">{{ errors.code.0 }}</span>
                        {% else %}
                            <span class="error-info">{{ code_error.error_code_info }}</span>
                        {% endif %}
                   </div>
                    <div class="register-submit">
                        <input type="button" value="重置">
                        <input type="submit" value="注册">
                    </div>
                </form>
            </div>
        </div>
      <script type="text/javascript" src="/statics/js/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="/statics/js/one.js"></script>
    </body>
</html>

后台处理:

def register(request):
    if request.method == 'POST':
        register_obj = RegisterForm(request.POST)
        ret = register_obj.is_valid()
        if ret:
            input_code = register_obj.cleaned_data['code']
            old_code = request.session['code']
            if input_code.upper() == old_code.upper():
                request.session['is_login'] = True
                print(register_obj.cleaned_data)
                return HttpResponseRedirect('/manager/')
            else:
                error_code_info = {'error_code_info': '验证码输入错误'}
                return render(request, 'forms/register.html', {'errors': register_obj.errors,
                                                               'code_error': error_code_info, 'form': register_obj})
        else:
            return render(request, 'forms/register.html', {'errors': register_obj.errors, 'form': register_obj})
    else:
        register_obj = RegisterForm()
        return render(request, 'forms/register.html', {'form': register_obj})

页面效果:

 

posted @ 2017-10-26 13:27  TianTianLi  阅读(914)  评论(0编辑  收藏  举报