型号:
class MyModel(models.Model):
status = models.ForeignKey(Status, on_delete=models.PROTECT, null=True, blank=True)
date = models.DateField()
形式:
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = '__all__'
def clean_date(self):
cd = self.cleaned_data
status = cd.get('status')
date = cd.get('date')
if not date and status == 1:
raise forms.ValidationError((mark_safe('<p class="text-danger">When status is .... You must add date </p>')))
return date
我的清洁功能不起作用。怎么回事?你能救我吗?
答案 0 :(得分:2)
如果您是cleaning fields that depend on each other,那么您应该覆盖clean
方法,而不是clean_date
。
由于status
是外键,因此永远不会等于1
。也许你想检查主键,在这种情况下你应该使用status.pk
。
def clean(self):
cleaned_data = super(ContactForm, self).clean()
status = cleaned_data.get('status')
date = cleaned_data.get('date')
if not date and status.pk == 1:
raise forms.ValidationError((mark_safe('<p class="text-danger">When status is .... You must add date </p>')))
return cleaned_data