2013-05-19 89 views
0

我想在我的模型clean()方法中更改field的「required」屬性。需要的模型字段

這裏是我的模型:從視圖中添加一個新的參數

class SomeModel(models.Model): 
    type = models.CharField() 
    attr1 = models.ForeignKey(Attr1, blank=True, null=True) 
    attrs2 = models.ForeignKey(Attr2, blank=True, null=True) 

現在,我在我的ModelForm __init__這樣做。 它動態設置所需的字段。

我可以在我的模型中實現相同嗎?我正在使用django-rest-framework API(它使用ModelForm),因此full_clean()(包括clean_fields()clean())將會運行。

說我想要attr1/attr2字段,如果類型以字符串開頭。

我知道我可以做這個檢查Model.clean(),但它會降落到NON_FIELD_ERRORS然後。

def clean(self): 
    if self.type.startswith("somestring"): 
     if self.attr1 is None and self.attr2 is None: 
      raise ValidationError("attr1 and attr2 are required..") 

我寧願看到這些錯誤連接到attR1和attR2位CRC錯誤與簡單的「這是必須填寫」(標準「要求的」 Django的錯誤)。

+1

看吧http://stackoverflow.com/questions/16609703/django-validating-several-fields – stalk

回答

0

這裏是我很好地工作代碼示例:

def clean(self): 
     is_current = self.cleaned_data.get('is_current',False) 
     if not is_current: 
      start_date = self.cleaned_data.get('start_date', False) 
      end_date = self.cleaned_data.get('end_date', False) 
      if start_date and end_date and start_date >= end_date: 
       self._errors['start_date'] = ValidationError(_('Start date should be before end date.')).messages 
     else: 
      self.cleaned_data['end_date']=None 
     return self.cleaned_data 
相關問題