2009-09-10 75 views
4

當另一個[關聯]字段具有特定值時,如何將強制性字段設置爲非強制性的?Django管理員:強制性非強制性字段

假設我有以下型號:

class foo(models.Model): 
    bar = models.CharField(max_length=200) 
    foo_date = models.DateTimeField() 

當我保存和欄包含一定的價值,我想foo​​_date成爲非強制性。我如何實現這一目標?謝謝。

回答

3

T.Stone是正確的。這是你如何使用模式的形式做到這一點:

class foo(models.Model): 
    bar = models.CharField(max_length=200) 
    foo_date = models.DateTimeField() 

class ClientAdmin(MyModelAdmin): 
    form = FooModelForm 

class FooModelForm(forms.ModelForm): 

    def clean(self): 
     cleaned_data = self.cleaned_data 
     if cleaned_data.get("bar") == 'some_val' and not cleaned_data.get('foo_date'): 
      msg = 'Field Foo Date is mandatory when bar is some_val' 
      self._errors[field] = ErrorList([msg]) 
      del cleaned_data[field] 
     return cleaned_data 

http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

2

我認爲這只是將foo_barr設置爲blank = True,然後爲Admin模型實施您自己的表單和自定義驗證。看到這部分的文檔 - Adding custom validation to admin