forms组件

forms组件

 

1 校验字段功能

 

针对一个实例:注册用户讲解。

 

模型:models.py

class UserInfo(models.Model):
name=models.CharField(max_length=32)
pwd=models.CharField(max_length=32)
email=models.EmailField()

模板文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<form action="" method="post">
    {% csrf_token %}
    <div>
        <label for="user">用户名</label>
        <p><input type="text" name="name" id="name"></p>
    </div>
    <div>
        <label for="pwd">密码</label>
        <p><input type="password" name="pwd" id="pwd"></p>
    </div>
    <div>
        <label for="r_pwd">确认密码</label>
        <p><input type="password" name="r_pwd" id="r_pwd"></p>
    </div>
     <div>
        <label for="email">邮箱</label>
        <p><input type="text" name="email" id="email"></p>
    </div>
    <input type="submit">
</form>

</body>
</html>

 

视图函数

# forms组件
from django import forms
from django.forms import widgets

wid_01=widgets.TextInput(attrs={"class":"form-control"})
wid_02=widgets.PasswordInput(attrs={"class":"form-control"})

class UserForm(forms.Form):
    name=forms.CharField(max_length=32,
                         widget=wid_01
                         )
    pwd=forms.CharField(max_length=32,widget=wid_02)
    r_pwd=forms.CharField(max_length=32,widget=wid_02)
    email=forms.EmailField(widget=wid_01)
    tel=forms.CharField(max_length=32,widget=wid_01)



def register(request):

    if request.method=="POST":
        form=UserForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)       # 所有干净的字段以及对应的值
        else:
            print(form.cleaned_data)       #
            print(form.errors)             # ErrorDict : {"校验错误的字段":["错误信息",]}
            print(form.errors.get("name")) # ErrorList ["错误信息",]
        return HttpResponse("OK")
    form=UserForm()
    return render(request,"register.html",locals())

 

 

2 渲染标签功能

渲染页面方式一
            <h1>渲染页面方式一</h1>
            <form action="" method="post" novalidate>
                <p>{{ form_obj.name.label }}:{{ form_obj.name }} <span
                        class="pull-right">{{ form_obj.name.errors.0 }}</span></p>
                <p>密码:{{ form_obj.pwd }}<span class="pull-right">{{ form_obj.pwd.errors.0 }}</span></p>
                <p>确认密码:{{ form_obj.re_pwd }}<span class="pull-right">{{ form_obj.re_pwd.errors.0 }}{{ errors }}</span></p>
                <p>邮箱{{ form_obj.email }}<span class="pull-right">{{ form_obj.email.errors.0 }}</span></p>
                <input type="submit">
            </form>

 

渲染页面方式二
            <form action="" method="post" novalidate>
                {% for foo in form_obj %}
                    <div>{{ foo.label }}{{ foo }}<span class="pull-right">{{ foo.errors }}</span></div>

                {% endfor %}
                <input type="submit">

 

渲染页面方式三
            <form action="" method="post">
                {{ form_obj.as_p }}
            </form>

 

3 渲染错误信息功能(错误信息返回到前台)

视图层

from django import forms

class RegForm(forms.Form):
    name = forms.CharField(required=True, max_length=10, min_length=2, label='用户名',
                           error_messages=
                           {'required': '该字段必填', 'max_length': '太长了', 'min_length': '太短了'})
    pwd = forms.CharField(max_length=10, min_length=2, label='密码')
    re_pwd = forms.CharField(max_length=10, min_length=2, label='确认密码')
    email = forms.EmailField(label='邮箱', error_messages={'required': '该字段必填', 'invalid': '不符合邮箱格式'})

 

模板层

            <h1>渲染页面方式一</h1>
            <form action="" method="post" novalidate>
                <p>{{ form_obj.name.label }}:{{ form_obj.name }} <span
                        class="pull-right">{{ form_obj.name.errors.0 }}</span></p>
                <p>密码:{{ form_obj.pwd }}<span class="pull-right">{{ form_obj.pwd.errors.0 }}</span></p>
                <p>确认密码:{{ form_obj.re_pwd }}<span class="pull-right">{{ form_obj.re_pwd.errors.0 }}{{ errors }}</span></p>
                <p>邮箱{{ form_obj.email }}<span class="pull-right">{{ form_obj.email.errors.0 }}</span></p>
                <input type="submit">
            </form>
            <hr>
            <h1>渲染页面方式二</h1>
            <form action="" method="post" novalidate>
                {% for foo in form_obj %}
                    <div>{{ foo.label }}{{ foo }}<span class="pull-right">{{ foo.errors }}</span></div>

                {% endfor %}
                <input type="submit">

 

4 组件的参数配置

给前端的标签添加属性

视图层

from django.forms import widgets

class RegForm(forms.Form):
    name = forms.CharField(required=True, max_length=10, min_length=2, label='用户名',
                           error_messages=
                           {'required': '该字段必填', 'max_length': '太长了', 'min_length': '太短了'},
                           widget=widgets.TextInput(attrs={'class':'form-control error','aa':'xxx'})
                           )
    pwd = forms.CharField(max_length=10, min_length=2, label='密码',widget=widgets.PasswordInput(attrs={'class':'form-control error','aa':'xxx'}))
    re_pwd = forms.CharField(max_length=10, min_length=2, label='确认密码',widget=widgets.PasswordInput(attrs={'class':'form-control error','aa':'xxx'}))
    # xx = forms.CharField(max_length=10, min_length=2, label='确认密码',widget=widgets.CheckboxInput())
    email = forms.EmailField(label='邮箱', error_messages={'required': '该字段必填', 'invalid': '不符合邮箱格式'},widget=widgets.EmailInput(attrs={'class':'form-control error','aa':'xxx'}))

 

 

5 局部钩子  自定义校验规则

6 全局钩子 自定义校验规则

视图层

from django import forms
from django.forms import widgets

from django.core.exceptions import  ValidationError

class RegForm(forms.Form):
    name = forms.CharField(required=True, max_length=10, min_length=2, label='用户名',
                           error_messages=
                           {'required': '该字段必填', 'max_length': '太长了', 'min_length': '太短了'},
                           widget=widgets.TextInput(attrs={'class':'form-control error','aa':'xxx'})
                           )
    pwd = forms.CharField(max_length=10, min_length=2, label='密码',widget=widgets.PasswordInput(attrs={'class':'form-control error','aa':'xxx'}))
    re_pwd = forms.CharField(max_length=10, min_length=2, label='确认密码',widget=widgets.PasswordInput(attrs={'class':'form-control error','aa':'xxx'}))
    # xx = forms.CharField(max_length=10, min_length=2, label='确认密码',widget=widgets.CheckboxInput())
    email = forms.EmailField(label='邮箱', error_messages={'required': '该字段必填', 'invalid': '不符合邮箱格式'},widget=widgets.EmailInput(attrs={'class':'form-control error','aa':'xxx'}))
    # 局部钩子(多了一个我自己写校验规则的方式)
    # def clean_pwd(self): 固定这种格式
    def clean_name(self):
        name=self.cleaned_data.get('name')
        user=UserInfo.objects.filter(name=name).first()
        if user:
            raise ValidationError('用户已经存在')
        else:
            if name.startswith('sb'):
                raise ValidationError('不能以sb开头')
            return name
    # 全局钩子 校验两次密码是否一致
    def clean(self):
        pwd=self.cleaned_data.get('pwd')
        re_pwd=self.cleaned_data.get('re_pwd')
        if pwd and re_pwd:
            if pwd==re_pwd:
                return self.cleaned_data
            else:
                raise ValidationError('两次密码不一致')

 

 

posted @ 2018-09-18 13:10  xujinjin  阅读(92)  评论(0编辑  收藏  举报