3.1 调用模块
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
3.2 定义类
widget_usr = widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '用户名'})
widget_pwd = widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': '用户名'})
class UserForm(forms.Form):
usr = forms.CharField(min_length=4, max_length=20, label='用户名', widget_usr)
pwd = forms.CharField(min_length=6, label='密码', widget_pwd)
email = forms.EmailField(error_messages={'required': '不能为空','invalid':'格式错误'})
def clean_usr(self):
val = self.cleaned_data.get('usr')
ret = User.objects.filter(username=val)
if not ret:
return val
else:
raise ValidationError('用户已注册')
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
else:
raise ValidationError('密码不一致')
3.3 校验功能
if request.method == "POST":
usr = request.POST.get('usr')
pwd = request.POST.get('pwd')
form = UserForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
User.objects.create_user(username=usr, password=pwd)
return redirect('/login/')
else:
print(form.cleaned_data)
print(form.errors)
print(form.errors.get('key')[0])
return render(request, 'reg.html', locals())
form = UserForm()
return render(request, "reg.html", locals())
3.4 渲染标签功能
{{ form.usr }}
<input type="text" name="usr" class="form-control" placeholder="用户名" required="" id="id_usr">
{% for field in form %}
<div>
<lable for="{{ field.auto_id }}">{{ field.lable }}</lable>
{{ field }}
</div>
{% endfor %}
{{ form.as_p }}
3.5 显示错误信息
{% for field in form %}
<div>
<lable for="{{ field.auto_id }}">{{ field.lable }}</lable>
{{ field }}
<span>{{ field.errors.0 }}</span>
</div>
{% endfor %}