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