Django Form two

Django_Form:

    1.class TeacherNewForm(Form):

        username = fields.CharField(

            required=True,

            error_messages={'required': '用户名不能为空'},

            widget=widgets.TextInput(attrs={'placeholder': '用户名', 'class': 'form-control'})

        )  # 不能为空

        password = fields.CharField(required=True, error_messages={'required': '密码不能为空'},

             widget=widgets.TextInput(attrs={'placeholder': '密码', 'class': 'form-control'}))  # 不能为空

        email = fields.EmailField(required=True, error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'},

            widget=widgets.EmailInput(

            attrs={'placeholder': '邮箱', 'class': 'form-control'}))  # 不能为空,且邮箱格式

        cls_list = fields.MultipleChoiceField(choices=[])

        def __init__(self,*args,**kwargs):

            super().__init__(*args,**kwargs)

            self.fields['cls_list'].choices = models.ClassList.objects.values_list('id','caption')

           

    2.# 显示input,并且将数据库中的默认值填写到input框中

     form = TeacherForm(initial={'username':obj.username,'password':obj.password,'email':obj.email})

   

    3.class DiyForm(forms.Form):

        # 类中创建字段  例如 IntegerField包含了正则表达式

        user = fields.CharField(

            max_length=18,

            min_length=6,

            required=True,

            error_messages={

                'max_length': '用户名过长',

                'min_length': '用户名过短',

                'required': '用户名不能为空',

                'invalid': '输入类型错误'

            }

        )

       

    4.import uuid

        data = uuid.uuid4() '16fd2706-8baf-433b-82eb-8c7fada847da'

       

    5.# 多选checkbox,值为列表

        user = fields.MultipleChoiceField(

        initial=[2, ],

        choices=((1, '上海'), (2, '北京'),),

        widget=widgets.CheckboxSelectMultiple

       

    6.class FInfo(forms.Form):#从数据库实时获取数据

        authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())

       

     推荐使用:必须使用values_list,放回元组的类型[(1,"讲师"),(2,"班主任"),(3,"管理员")]

        classteacher_id = fields.ChoiceField(choices=[])

        def __init__(self,*args,**kwargs):   #重写init方法,时时更新

            super().__init__(*args,**kwargs)   #继承父类

            self.fields["classteacher_id"].choices = models.UserInfo.objects.filter(ut_id = settings.ROLE_CLASSTEACHER).values_list('id', "username")

       

    7.自定义校验

        .class MyForm(Form):

            phone = fields.CharField(

            validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^188[0-9]+{9}$', '数字必须以188开头')],

           

        .def mobile_validate(value):

            mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')

            if not mobile_re.match(value):

                raise ValidationError('手机号码格式错误')

               

        phone = fields.CharField(validators=[mobile_validate, ],

                            error_messages={'required': '手机不能为空'},

                            widget=widgets.TextInput(attrs={'class': "form-control",

                                                          'placeholder': u'手机号码'}))                                                       

    8.clean_field:#在form验证完后验证相对应的字段

        def clean_user(self): #必须有返回值,只能拿当前字段

            """

            Form中字段中定义的格式匹配完之后,执行此方法进行验证

            :return:

            """

            v = self.cleaned_data['user']

            if models.UserInfo.objects.filter(user=v).count():

                raise ValidationError('此用户名已经存在')

            return v

           

    9.clean:#验证所有字段

            #设置整体错误,可以用来设置多个字段整体验证

            def clean(self):

                value_dict=self.cleaned_data

                v1 = value_dict.get('username')

                v2 = value_dict.get('user_id')

                if v1=='root' and v2==0:

                    raise ValidationError('整体错误信息')

                return self.cleaned_data

    10.中间件:

        请求 ->process_request1 ->process_request3 ->process_view1 ->process_view3 ->视图view

        ->prcess_exception3 ->prcess_exception1 ->process_response3 ->process_response1 ->请求

       

        class Md2(MiddlewareMixin):

            def process_request(self,request):

                print("Md2请求")

                # return HttpResponse("Md2中断")

            def process_response(self,request,response):

                print("Md2返回")

                return response

            def process_view(self, request, callback, callback_args, callback_kwargs):

                print("md2 process_view...")

            def process_exception(self):

                print("md1 process_exception...")

               

    11.认证使用

        form = TeacherForm(initial={"username":obj.username,"password":obj.password,"email":obj.email,

            "teacher_classes":[obj.id for obj in obj.teacher_classes.all()]}) #带有初始化的Form

        from = TeacherForm(dat = request.POST)

        from.is_valid()

        from.cleaned_data#一个列表

        form.as_json()

        from.errors #一个列表

        - 主动向form中添加错误信息

          # form.add_error('password','用户名或密码错误')

          form.add_error('password',ValidationError('用户名或密码错误'))

          这两个都可以,建议用第二个

猜你喜欢

转载自www.cnblogs.com/mihon/p/8980910.html
今日推荐