Forms组件

一、forms组件

1、校验数据

# 第一步需要一个form类
from django import forms

class MyForm(forms.Form):
     name = forms.CharField(max_length=6)
     password = forms.CharField(max_length=8,min_length=3)
     email = forms.EmailField(required=True)
# 第二步实例化form对象
    form_obj = MyForm({'name':'jason'})
            
# 第三步查看数据校验是否合法
    form_obj.is_valid()  # 只有当所有的字段都校验通过才会返回True
            
# 第四步查看校验错误的信息
    form_obj.errors  # 这个里面放的是所有校验未通过的字段及错误提示

{'name': ['Ensure this value has at most 6 characters (it has 7).'], 
'password': ['Ensure this value has at least 3 characters (it has 2).'], 
'email': ['Enter a valid email address.']} # 第五步查看校验通过的数据 form_obj.cleaned_data # 符合校验规则数据都会被放到该对象中 # form组件校验数据的规则从上往下依次取值校验 校验通过的放到cleaned_data 校验失败的放到errors # 注意: form中所有的字段默认都是必须传值的(required=True) 校验数据的时候可以都传(多传的数据不会做任何的校验,不会影响form校验规则)

2、渲染标签

from django import forms

class MyForm(forms.Form):
    username = forms.CharField(max_length=6, label='用户名')
    password = forms.CharField(max_length=8, min_length=3)
    email = forms.EmailField()

def reg(request):
    # 生成一个空对象
    form_obj = MyForm()
    return render(request, 'reg.html', locals())
views.py

reg.html:

<h1>第一种渲染标签的方式</h1>
{{ form_obj.as_p }}
{{ form_obj.as_ul }}

<h1>第二种渲染标签的方式</h1>
<form action="">
    <p>{{ form_obj.username.label }}{{ form_obj.username }}</p>
    <p>{{ form_obj.password.label }}{{ form_obj.password }}</p>
    <p>{{ form_obj.email.label }}{{ form_obj.email }}</p>
    <input type="submit">
</form>

<h1>第三种渲染标签的方式</h1>
<form action="" method="post">
    {% for foo in form_obj %}
    <p>{{ foo.label }}{{ foo }}</p>
    {% endfor %}
    <input type="submit">
</form>

3、展示数据

①前端取消校验

②展示数据输入是否合法

 

from django import forms


class MyForm(forms.Form):
    username = forms.CharField(max_length=6, label='用户名', error_messages={
        'max_length': '用户名最长为6位',
        'required': '用户名不能为空'
    })
    password = forms.CharField(max_length=8, min_length=3, error_messages={
        'max_length': '密码最长为8位',
        'required': '密码不能为空',
        'min_length': '密码最少3位'
    })
    email = forms.EmailField(error_messages={
        'required': '邮箱不能为空',
        'invalid': '邮箱格式不正确'
    })


def reg(request):
    # 生成一个空对象
    form_obj = MyForm()
    if request.method == 'POST':
        print(request.POST)
        form_obj = MyForm(request.POST)
        if form_obj.is_valid():
            print(form_obj.cleaned_data)
            models.User.objects.create(**form_obj.cleaned_data)
    return render(request, 'reg.html', locals())
views.py

reg.html:

<h1>第三种渲染标签的方式</h1>
<form action="" method="post" novalidate>
    {% for foo in form_obj %}
        <p>
            {{ foo.label }}{{ foo }}
            <span>{{ foo.errors.0 }}</span>
        </p>
    {% endfor %}
    <input type="submit">
</form>

 ③钩子函数

# 局部钩子函数 (单个字段的校验利用局部钩子函数)
    def clean_username(self):
        username = self.cleaned_data.get('username')
        if '666' in username:
            self.add_error('username', '敏感字词666')
        return username

# 全局钩子函数 (多个字段的校验利用全局钩子函数)
    def clean(self):
        password = self.cleaned_data.get('password')
        re_password = self.cleaned_data.get('re_password')
        if not password == re_password:
            self.add_error('re_password', '密码不一致')
        return self.cleaned_data

 ④设置标签样式

from django import forms
from django.forms import widgets  # 将密码设置成密文导入的模块
class MyForm(forms.Form):
    username = forms.CharField(max_length=6, label='用户名', error_messages={
        'max_length': '用户名最长为6位',
        'required': '用户名不能为空'
    })
    password = forms.CharField(max_length=8, min_length=3, error_messages={
        'max_length': '密码最长为8位',
        'required': '密码不能为空',
        'min_length': '密码最少3位'
    }, widget=widgets.PasswordInput(attrs={'class': 'c2 form-control'}))
    re_password = forms.CharField(max_length=8, min_length=3, error_messages={
        'max_length': '确认密码最长为8位',
        'required': '确认密码不能为空',
        'min_length': '确认密码最少3位'
    }, widget=widgets.PasswordInput)
    email = forms.EmailField(error_messages={
        'required': '邮箱不能为空',
        'invalid': '邮箱格式不正确'
    })
    gender = forms.ChoiceField(
        choices=((1, ""), (2, ""), (3, "保密")),
        label="性别",
        initial=3,       # 默认值
        widget=forms.widgets.RadioSelect()
    )
    hobby = forms.ChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
        label="爱好",
        initial=3,       # 默认值
        widget=forms.widgets.Select()
    )
    hobby1 = forms.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
        label="爱好",
        initial=[1, 3],  # 默认值
        widget=forms.widgets.SelectMultiple()
    )
    keep = forms.ChoiceField(
        label="是否记住密码",
        initial="checked",  # 默认值
        widget=forms.widgets.CheckboxInput()
    )

 

 

posted @ 2019-06-17 20:06  TianShu  Views(198)  Comments(0Edit  收藏  举报