DAY19-Django之form组件补充

问题1:注册页面输入为空,报错:keyError:找不到password

def clean(self):

    print("---" ,self.cleaned_data)
    #  if self.cleaned_data["password"]==self.cleaned_data["repeat_password"]:        
    #  报错原因:self.cleaned_data是干净数据,如果页面没有输入内容,则self.cleaned_data没有password。
    改如下:
    if self.cleaned_data.get("password" )==self.cleaned_data.get("repeat_password"):
        return self.cleaned_data
    else:
        raise ValidationError("两次密码不一致")

  2  为什么要用全局clean():

按子段顺序一一校验,即校验到username时,你无法使用self.cleaned_data.get("password")。

而局部钩子使用完,到全局时,已经可以使用所有的self.cleaned_data

3

自定义验证规则

单选和多选框,实时获取数据库数据:

方式一:重构构造方法(推荐):

方法一:重构构造方法(推荐)
    class ClassesForm(Form):
    name = fields.CharField(
        required=True,  # 必填字段
        error_messages={"required": "姓名不能为空!!"},  # 显示中文错误提示
        widget=widgets.TextInput(attrs={"placeholder": "姓名", "class": "form-control"}),  # 自动生成input框
    )
    # 如果直接定义成classteacher_id,,_id 的形式,这样你添加数据的时候不会时时更新,所以在下面定义一个重写的方法
    # classteacher_id = fields.ChoiceField(choices= models.UserInfo.objects.filter(ut_id = settings.ROLE_CLASSTEACHER).values_list('id', "username"))

        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")
    注意:
        要是这样:fields.ChoiceField(choices=[])
        注意choices里面传[(1,"讲师"),(2,"班主任"),(3,"管理员")]所以数据库里取的时候得用values_list

 方式二:

方法二:ModelChoiceField(不推荐),queryset
    from django.forms.models import ModelChoiceField  #先导入
    class ClassForm(Form):
        caption = fields.CharField(error_messages={'required':'班级名称不能为空'})
        # headmaster = fields.ChoiceField(choices=[(1,'娜娜',)])  #(列表加元组,1作为value,娜娜作为text文本内容)
        headmaster_id = ModelChoiceField(queryset=models.UserInfo.objects.filter(ut_id=2))

多选:

ModelMultipleChoiceField

from django.views import View
from django import forms
from .models import Publish,Author,Book


'''
class BookForm(forms.Form):
    title=forms.CharField()
    price=forms.DecimalField()
    publishDate=forms.DateField()

    #state=forms.ChoiceField(choices=[(1,"已出版"),(2,"未出版")])
    publish=forms.ModelChoiceField(queryset=Publish.objects.all())
    authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all())
原文地址:https://www.cnblogs.com/guoyunlong666/p/9040231.html