form组件
在需要使用用户认证组件的app下创建my_form.py
# my_form.py
from django.forms import widgets # 用于规定type
from django import forms # forms组件
from blog.models import UserInfo # 引入表进行创建钩子
from django.core.exceptions import ValidationError # 钩子捕获异常
class UserForm(forms.Form):
user = forms.CharField(max_length=32, label="用户名", widget=widgets.TextInput(attrs={"class": "form-control"}),
error_messages={"required": "该字段不能为空"})
pwd = forms.CharField(max_length=32, label="密码", widget=widgets.PasswordInput(attrs={"class": "form-control"}),
error_messages={"required": "该字段不能为空"})
re_pwd = forms.CharField(max_length=32, label="确认密码", widget=widgets.PasswordInput(attrs={"class": "form-control"}),
error_messages={"required": "该字段不能为空"})
email = forms.EmailField(max_length=32, label="邮箱", widget=widgets.EmailInput(attrs={"class": "form-control"}),
error_messages={"required": "该字段不能为空"})
# 二次校验
def clean_user(self):
user = self.cleaned_data.get("user")
userinfo = UserInfo.objects.filter(username=user).first()
if not userinfo:
return user
else: # 已有人注册过了
raise ValidationError("该用户已被注册") # 一定要用raise ValidationError("xxxxx")
def clean(self): # 全局钩子,键__all__
pwd = self.cleaned_data.get("pwd") # 所有干净的字段以及对应的值的字典
re_pwd = self.cleaned_data.get("re_pwd")
# 有多个错误信息需要再多一个判断
if pwd and re_pwd: # 两个都有值时
if pwd.upper() == re_pwd.upper():
return self.cleaned_data
else:
raise ValidationError("两次密码不一致")
else:
return self.cleaned_data
# register.html
{% for field in form %}
<div class="form-group">
<label for="{{ field.auto_id }}">{{ field.label }}</label>#.auto_id生成id_field,用于label对应input的id
{{ field }} <span class="error pull-right"></span>
</div>
{% endfor %}
#views.register
if form.is_valid(): # 如果有值
response["user"] = form.cleaned_data.get("user")
# 生成用户信息
user = form.cleaned_data.get("user")
pwd = form.cleaned_data.get("pwd")
email = form.cleaned_data.get("email")
avatar_obj = request.FILES.get("avatar") # 拿头像
print(form.cleaned_data)
# 代码优化
extra = {} # 扩展字段
if avatar_obj: # 如果用户传了头像
extra["avatar"] = avatar_obj # 扩展字段赋值给字典
UserInfo.objects.create_user(username=user, password=pwd, email=email, **extra) # 传字典**{}
else: # 如果没有值,则说明有错误form.errors拿到所有错误的字典
print(form.cleaned_data)
print(form.errors)
response["msg"] = form.errors