三、form组件


返回

3.1 调用模块

from django import forms
from django.forms import widgets  # 属性
from django.core.exceptions import ValidationError  # 钩子

3.2 定义类

# 1、设置标签属性
widget_usr = widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '用户名'})
widget_pwd = widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': '用户名'})

class UserForm(forms.Form):
  	# 2、校验字符串
    usr = forms.CharField(min_length=4, max_length=20, label='用户名', widget_usr)
    pwd = forms.CharField(min_length=6, label='密码', widget_pwd)
    # 2、校验邮箱  
    email = forms.EmailField(error_messages={'required': '不能为空','invalid':'格式错误'})
		
    # 7、局部钩子
    def clean_usr(self):  # 源码:'clean_%s' % name
        val = self.cleaned_data.get('usr')
        ret = User.objects.filter(username=val)
        if not ret:
            return val  # 源码:self.cleaned_data[name] = val
        else:
            raise ValidationError('用户已注册')
		
    # 7、全局钩子
    def clean(self):
        pwd = self.cleaned_data.get('pwd')
        r_pwd = self.cleaned_data.get('r_pwd')
        if pwd == r_pwd:
            return self.cleaned_data  # 源码:self.cleaned_data = cleaned_data
        else:
            raise ValidationError('密码不一致')

3.3 校验功能

if request.method == "POST":
    usr = request.POST.get('usr')
    pwd = request.POST.get('pwd')
    # 5、参数是字典,只匹配UserForm里的所有字段
    form = UserForm(request.POST)
    # 6、所有字段规则校验都通过
    if form.is_valid():  # 源码
        print(form.cleaned_data)  # 所有正确信息:key:value
        User.objects.create_user(username=usr, password=pwd)
        return redirect('/login/')
    else:
        print(form.cleaned_data)  # 正确信息:'key':'value'
        print(form.errors)  # 错误信息:'key':['错误信息']
        print(form.errors.get('key')[0])  # 错误信息字符串
        return render(request, 'reg.html', locals())
# 3、form传入reg.html文件,渲染标签用
form = UserForm()
return render(request, "reg.html", locals())

3.4 渲染标签功能

<!-- 4、方式一 -->
{{ form.usr }}
<!-- 等同于以下代码 -->
<input type="text" name="usr" class="form-control" placeholder="用户名" required="" id="id_usr">

<!-- 4、方式二(推荐) -->
{% for field in form %}
<div>
  	<lable for="{{ field.auto_id }}">{{ field.lable }}</lable>
  	{{ field }}
</div>
{% endfor %}

<!-- 4、方式三 -->
{{ form.as_p }}

3.5 显示错误信息

{% for field in form %}
<div>
  	<lable for="{{ field.auto_id }}">{{ field.lable }}</lable>
  	{{ field }}
  	<!-- 3、错误信息 -->
  	<span>{{ field.errors.0 }}</span>
</div>
{% endfor %}
返回