Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 700
B Robster Avatar asked Aug 26 '12 05:08

B Robster


1 Answers

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])
like image 131
jrobs585 Avatar answered Oct 05 '22 23:10

jrobs585