Django--Form小结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Django Form组件
    1 验证
    2 生成HTML(保留上次输入内容)
    3 初始化默认值
     
FORM重点
    -字段
        ChoiceField   单选框
        MultipleChoiceField  多选框
        CharField
        IntegerField
        DecimalField  小数
        DateField
        DateTimeField
        EmailField
        GenericIPAddressField  IP
         
        RegexField  自定义正则
        

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
         
Form组件扩展:
    1 简单扩展
        利用Form组件自带的正则扩展
            a,方式一,这种可以写多个正则表达式
            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.CharField(
                    validators=[RegexValidator(r'^[0-9]+$','请输入数字'),RegexValidator(r'^159[0-9]+$','数字必须为159开头')]
                )
             
            b,方式二,这种只能有一个正则表达式
            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]+$')
             
         
    2 基于原码流程的扩展
        单字段
        from django.core.exceptions import NON_FIELD_ERRORS,ValidationError
        class AjaxForm(forms.Form):
            price = fields.CharField()
            user_id = fields.IntegerField(
                widget=widgets.Select()
 
            )
 
            def __init__(self, *args, **kwargs):  # 实时根据数据库更新,每次运行时,都会执行__int__(),得到choices
                super(AjaxForm, self).__init__(*args, **kwargs)
                self.fields['user_id'].widget.choices = models.UserInFo.objects.values_list('id', 'username')
 
 
            #自定义方法,来判断输入的数据是否在数据库中存在
            #自定义 clean_字段名
            #必须有返回值 sell.clean_data['username]
            #如果出错,直接raise ValidationError
            def clean_username(self):
                v = self.cleaned_data['username']
                if models.UserInFo.objects.filter(username=v).count():
                    # 整体错了
                    # 自己详细错误信息
                    raise ValidationError('用户名已经存在')
                return self.cleaned_data['username']
 
            def clean_user_id(self):
                return self.cleaned_data['user_id']
 
        

  

1
2
3
4
5
6
7
8
9
3 整体错误的判断
    <br>     
    def clean(self):
    value_dict = self.clean_data
    v1=value_dict.get('username')
    v2=value_dict.get('user_id')
    if v1== 'root' and v2==1:
        raise ValidationError('整体错误信息')
    return self.clean_data

  


posted @   阜阳小全  阅读(107)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示