Django表单中的空字段验证

时间:2018-10-09 06:24:10

标签: forms python-2.7 validation django-forms django-1.9

我正在尝试过滤一个空字段并在forms.py中对其进行验证,但出现以下错误:

  

无法分配无:“ TeacherAttendance.teacher”不允许使用空值。

但是我正在按照以下针对教师领域的表格进行验证。它应该生成“请选择老师”的确认警告。但是它没有做。 如果我没有从教师字段中选择一位教师,则应验证教师的空值,然后返回带有警告警告的表格。

class TeacherAttendanceForm(forms.ModelForm):

class Meta:
    model = TeacherAttendance
    fields = ('time', 'attendance', 'teacher','dailynote','writer',)
    exclude = ['uuid', 'notedate',]
    widgets = {
        'attendance': forms.RadioSelect(renderer=HorizontalRadioRenderer),
        'dailynote': forms.Textarea(attrs={'rows': 10}),
        'writer': forms.Textarea(attrs={'rows': 1}),
        'uuid': forms.HiddenInput(),
        'semester': forms.HiddenInput(),
    }

def clean(self):
    if str(self.cleaned_data['time']) == "-----------":
        raise forms.ValidationError('Please choose time.')
    if self.cleaned_data['dailynote'] == "":
        raise forms.ValidationError('Please enter note.')
    if not self.cleaned_data['teacher']:
        raise forms.ValidationError('Please choose teacher .')

我的模型在下面,教师字段是一个下拉列表,显示所有教师。

class TeacherAttendance(BaseModel):
teacher = models.ForeignKey(Staff, blank=True, verbose_name=_("Choose Teacher"))
attendance = models.CharField(choices=TEACHER_ATTENDANCE, default="YOK", max_length=20, verbose_name=_("Attendance"))
time = models.CharField(choices=TIME, default="-------------", max_length=20, verbose_name=_("Time"))
dailynote = models.TextField(null=True, blank=True, verbose_name=_("Add Note"))
notedate = models.DateField(auto_now_add=True, db_index=True, verbose_name=_("Date"))
writer = models.TextField(null=True, blank=True, verbose_name=_("Writer"))

class Meta:
    unique_together = ("teacher", "attendance", "notedate")
    index_together = [["teacher", "notedate", ], ]

def __unicode__(self):
    return "%s / %s / %d " % (self.teacher, self.notedate, self.attendance)  

1 个答案:

答案 0 :(得分:0)

我通过更改模型中的以下字段解决了这个问题:

  

teacher = models.ForeignKey(Staff,blank = True,verbose_name = _(“ Choose Teacher”))

至:

  

teacher = models.ForeignKey(Staff,blank = True,null = True,verbose_name = _(“ Choose Teacher”))

通过在字段中添加“ null = True”。可能是在进行表单验证之前先查看模型字段。