2013-10-21 11 views
0
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字段。如何將django錯誤驗證綁定到特定的ForeignKey字段,而不是整個模型

我也不認爲驗證器可以掛鉤到ForeignKey字段。

回答

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 
+0

這將是很好,如果這個代碼可以在模型內被封裝,不會的ModelForm。但是,這工作。謝謝! –

+0

如果你需要在幾個地方使用它,你可以始終從這個類繼承,並在Meta內部類中傳遞表單所用的模型。 – Brandon

相關問題