django - Model field required on -
i change "required" property field in model clean() method.
here's model:
class somemodel(models.model): type = models.charfield() attr1 = models.foreignkey(attr1, blank=true, null=true) attrs2 = models.foreignkey(attr2, blank=true, null=true)
right doing in modelform __init__
adding new parameter view. dynamically sets required fields.
can achieve same in models? using django-rest-framework api (it's using modelform) full_clean()
(that includes clean_fields()
, clean()
) run.
say attr1/attr2 fields required if type starts string.
i know can check in model.clean()
land non_field_errors
then.
def clean(self): if self.type.startswith("somestring"): if self.attr1 none , self.attr2 none: raise validationerror("attr1 , attr2 required..")
i rather see these errors attached attr1 , attr2 field errors simple "this field required" (standard "required" django error).
here code example work fine me:
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 , end_date , start_date >= end_date: self._errors['start_date'] = validationerror(_('start date should before end date.')).messages else: self.cleaned_data['end_date']=none return self.cleaned_data
Comments
Post a Comment