0

I would like to change "required" property for field in my model clean() method.

Here's my 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 now I am doing this in my ModelForm __init__ by adding a new parameter from view. It dynamically sets required for fields.

Can I achieve the same in my models? I am using django-rest-framework for API (it's using a ModelForm) so full_clean() (that includes clean_fields() and clean()) will be run.

Say I would like attr1/attr2 fields required if type starts with some string.

I know I can do this check in Model.clean() but it will land into NON_FIELD_ERRORS then.

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..")

I would rather see these errors attached to attr1 and attr2 field errors with simple "This field is required" (standard "required" django error).

4

1 回答 1

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
于 2013-05-20T14:29:14.290 回答