如何将django错误验证绑定到特定的ForeignKey字段,而不是整个模型
若要有效,Invoice.from_business.is_distributor必须为True。我可以在clean()中执行此操作,但此错误将与整个模型相关,而不是特定的from_业务字段如何将django错误验证绑定到特定的ForeignKey字段,而不是整个模型,django,validation,Django,Validation,若要有效,Invoice.from_business.is_distributor必须为True。我可以在clean()中执行此操作,但此错误将与整个模型相关,而不是特定的from_业务字段 我也不认为验证器可以钩住ForeignKey字段 您可以使用以下方法轻松访问外键字段的实例并验证属性: 如果这段代码可以封装在模型中,而不是封装在ModelForm中,那就太好了。然而,这是可行的。非常感谢。如果您需要在多个地方使用它,您可以始终从这个类继承,并在元内部类中传递表单用于哪个模型。 class
我也不认为验证器可以钩住ForeignKey字段 您可以使用以下方法轻松访问外键字段的实例并验证属性:
如果这段代码可以封装在模型中,而不是封装在ModelForm中,那就太好了。然而,这是可行的。非常感谢。如果您需要在多个地方使用它,您可以始终从这个类继承,并在元内部类中传递表单用于哪个模型。
class Business(models.Model):
is_distributor = models.BooleanField()
class Invoice(models.Model):
from_business = models.ForeignKey(Business)
to_business = models.ForeignKey(Business)
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