B Robster
B Robster

Reputation: 42083

Django model field validation without a custom form

I am using a django DateField in my model.

class CalWeek(models.Model):
  start_monday = models.DateField(verbose_name="Start monday")

I have a custom validation method that is specific to my modelField: I want to make sure that it is actually a Monday. I currently have no reason to use a custom ModelForm in the admin--the one Django generates is just fine. Creating a custom form class just so i can utilize the clean_start_monday(self)1 sugar that django Form classes provide seems like a lot of work just to add some field validation. I realize I can override the model's clean method and raise a ValidationError there. However, this is not ideal: these errors get attributed as non-field errors and end up at the top of the page, not next to the problematic user input--not an ideal UX.

Is there an easy way to validate a specific model field and have your error message show up next to the field in the admin, without having to use a custom form class?

Upvotes: 15

Views: 10872

Answers (1)

jrobs585
jrobs585

Reputation: 326

You can look into Django Validators.

https://docs.djangoproject.com/en/dev/ref/validators/

You would put the validator before the class, then set the validator in the Field.

def validate_monday(date):
    if date.weekday() != 0:
        raise ValidationError("Please select a Monday.")

class CalWeek(models.Model):
    start_date = models.DateField(validators=[validate_monday])

Upvotes: 21

Related Questions