1
votes

I am trying to filter a null field and validate it in forms.py But i get below error :

Cannot assign None: "TeacherAttendance.teacher" does not allow null values.

But i am doing validation in the form as below for teacher field. It should generate "Please choose teacher" validation warning. But it is not doing. It should validate the null value for teacher and go back to form with a validation warning if i dont choose a teacher from teacher field.

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 .')

My model is below and teacher field is a dropdown filed that shows all 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

1 Answers

0
votes

I solved the question by changing below field in model :

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

to :

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

by adding "null=True" to the field. Probably it was first looking at the model field before doing form validation.