Django Form组件的扩展

Form组件扩展

 1.用Form组件自带的正则扩展

 通过Django内置的字段:Validators自定义验证规则

 方式一:

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator

class MyForm(forms.Form):
       Username = fields.CharField(
                validators =[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')],
       )

方式二:

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator
                 
class MyForm(Form):
      user = fields.RegexField(
r'^[0-9]+$',error_messages={'invalid1': '...','invalid2':'...'}
)

2.自定义方法单字段的判断 

class UserInfo(forms.Form):
    username = fields.CharField()
    user_id = fields.IntegerField(
        widget=(
            widgets.Select(choices=[(0, '证没那个'), (1, '网名'), (2, '刘敏'),])
        )
    )

# 在源码中出错会抛出一个 ValidationError 异常
 from django.core.exceptions import NON_FIELD_ERRORS, ValidationError    
      
    def clean_username(self):
     #只能取当前字段的值,不能取其它字段的值
    v = self.cleaned_data['username']
       #如果用户数大于0    
    if models.UserInfo.objects.filter(username=v).count():   
      raise ValidationError('用户名已存在') 
    return self.cleaned_data['username]

 自定义方法验证整体

    # django为我们预留了这个钩子函数,当所有clean_字段名 的方法结束后,会再执行这个函数
 """
        Hook for doing any extra form-wide cleaning after Field.clean() has been
        called on every field. Any ValidationError raised by this method will
        not be associated with a particular field; it will have a special-case
        association with the field named '__all__'.
        """
    def clean(self):
        # 获取所有通过验证的数据
        value_dict =self.cleaned_date
        v1 = value_dict.get('username')
        v2 = value_dict.get('user_id')
        if v1 == 'root' and v2 == 1:
        # 在前端取时,用__all__来取
            raise ValidationError('整体错误信息')
        return self.cleaned_data
#  当clean方法执行完成后,还会再执行这个方法,我们可以重写,没有返回值,一般不用
    def _post_clean(self):
         pass

  

posted @ 2020-02-26 13:36  Mr.toby  阅读(151)  评论(0编辑  收藏  举报