Django(36)forms组件

forms,一般用于用户注册的组件,有渲染标签功能,可以通过局部钩子与全局钩子校验input标签输入的内容

1,使用方式

在model中写好模型,

from django.db import models


class UserInfo(models.Model):
    username = models.CharField(verbose_name='用户名', max_length=32)
    password = models.CharField(verbose_name='密码', max_length=32)
    email = models.EmailField(verbose_name='邮箱', max_length=32)
    mobile_phone = models.CharField(verbose_name='手机号', max_length=32)

1.1重写一个类,继承forms.Form

class UserForm(BootStrapForm, forms.Form):
    username = forms.CharField(max_length=32,
                               error_messages={"required": "该字段不能为空"},
                               label="用户名",
                               widget=widgets.TextInput()
                               )
    password = forms.CharField(min_length=8,
                               max_length=32,
                               error_messages={
                                   'min_length': "密码长度不能小于8个字符",
                                   'max_length': "密码长度不能大于32个字符",
                                   "required": "该字段不能为空"
                               },
                               label="密码",
                               widget=widgets.PasswordInput()
                               )
    re_pwd = forms.CharField(······)
    email = forms.EmailField(·····)
    mobile_phone = forms.CharField(······)
    
    class Meta:
      model = UserInfo
      fields = "__all__"

1.2,views

 form = UserForm()
    return render(request, "register.html", {"form": form})

1.3,html

{% for field in form %}  
    <div class="form-group">
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {{ field }}
        <span class="error-msg"></span>
    </div>
{% endfor %}

2,全局校验

在字段里面添加限制

 mobile_phone = forms.CharField(label='手机号',
                                   validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'),
                                               ])
    password = forms.CharField(min_length=8,
                               max_length=32,
                               error_messages={
                                   'min_length': "密码长度不能小于8个字符",
                                   'max_length': "密码长度不能大于32个字符", },
                               label="密码",)
# 必须有min_length,才能在error_messages里面添加
class BootStrapForm(object):
    bootstrap_class_exclude = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if name in self.bootstrap_class_exclude:
                continue
            old_class = field.widget.attrs.get('class', "")
            field.widget.attrs['class'] = '{} form-control'.format(old_class)
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)
# 给所有的字段添加属性
class UserForm(BootStrapForm, forms.Form):

3,局部钩子

    def clean_username(self):
        username = self.cleaned_data['username']
        exists = models.UserInfo.objects.filter(username=username).exists()
        if exists:
            raise ValidationError('用户名已存在')
            # self.add_error('username','用户名已存在')
        return username

3.1,使用方式

clean_字段名

注意点,要按照顺序校验,验证前面数据是取不到后面的数据

    def clean_password(self):
        pwd = self.cleaned_data['password']
        # 加密 & 返回
        return encrypt.md5(pwd)

    def clean_re_pwd(self):
        pwd = self.cleaned_data.get('password')
        confirm_pwd = encrypt.md5(self.cleaned_data['re_pwd'])
        if pwd != confirm_pwd:
            raise ValidationError('两次密码不一致')
        return confirm_pwd

可以自定义顺序

   class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']
posted @ 2021-12-09 21:39  下个ID见  阅读(24)  评论(0)    收藏  举报