Search code examples
pythondjangodjango-modelsdjango-formsdjango-validation

Which is the best way to validate errors in Django?


I found that there is a lot of ways to validate errors in Django, I'm just wondering which one is preferable and why?

e.g.

  1. using clean in form, like:

        deadline = self.cleaned_data.get('deadline')
        if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today():
            raise forms.ValidationError(_('Deadline cannot be in past!'))
        return deadline
    
    
  2. before saving we can validate if there is any error and sending the instance if everything right, like:

     def save(self, force_insert=False, force_update=False, *args, **kwargs):
         if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today():
             raise forms.ValidationError(_('Deadline cannot be in past!'))
         else:
             super(MODEL, self).save(force_insert, force_update, *args, **kwargs)
    
  3. and not forgetting the validators in the model where I can use one in the filed it self like:

     deadline = models.DateTimeField(
                   verbose_name=_('deadline'),
                   validators=[MaxValueValidator(datetime.datetime.today())],
                   help_text=_('Note that the end time will be at the midnight of the day you picked.'),
    )
    

Also, we can do that in the forms in the class form we can check before saving if everything is right.

I want to know which is the best as a programmer and write a professional code.


Solution

  • In MVC, anything that touches the database should be in the model layer. You could have a method like 'is_valid_email(...)' on the User model and call that from your Form.

    Note that the Model layer doesn't mean that you have to have a Class per table in your database VS creating new classes.

    The Form is the Controller in DRF, I would go with option 1.