如何将django错误验证绑定到特定的ForeignKey字段,而不是整个模型

时间:2013-10-21 17:15:34

标签: django validation

class Business(models.Model):
    is_distributor = models.BooleanField()

class Invoice(models.Model):
    from_business = models.ForeignKey(Business)
    to_business = models.ForeignKey(Business)

要生效,Invoice.from_business.is_distributor必须为True。我可以在clean()中执行此操作,但此错误将与整个模型绑定,而不是特定的from_business字段。

我也不认为验证器可以挂钩到ForeignKey字段。

1 个答案:

答案 0 :(得分:1)

您可以轻松访问外键字段的实例并使用clean方法验证属性:

from django import forms

from your_app.models import Invoice


class InvoiceForm(forms.ModelForm):
    def clean(self):
        cleaned_data = self.cleaned_data()

        business = cleaned_data.get('business')
        if not business.is_distributor:
            self._errors['business'] = self.error_class(
                ['Business must be a distributor.'])
            del cleaned_data['business']

        return cleaned_data