[Django]-Separating form input and model validation in Django?

16👍

This is a very interesting question (for me).

In my opinion, all validation code should be moved to model code. This is the way to not break business rules. When validation code is in the model it is not possible to forget some validation in a new form or to have inconsistent rules in several forms.

I link to you ‘Django, Raise a validation error in a model’s save method’ question that is related to yours. Below question you can see how move code validations from forms to model. I hope that this brief introduction can helps to you.

From what framework you come? How validation rules are writen in your enviromnent?

9👍

I don’t agree with the accepted answer. I prefer to use model-level validation to avoid inconsistencies in models, and form-level validation for any site-specific restrictions.

Suppose we have a model for events, with datetime fields for the start and end time. Model validation would force us to have an end time that comes after the start time. However, I would leave it in the form to validate that the newly created event is not in the past. Therefore, if I ever have to add an event that occured in the past, I could use an admin-specific form that allows dates in the past, or simply add it straight to the database.

Thus, model validation should only check for values that are patently wrong. but if you ever need to do something funky (Unicode characters in a username for a bot, for example), it should let you do it, even if it’s only through the admin or the shell. I’ve read an answer on StackOverflow that suggested always using forms in backend code, filling fields with code like form["field"] = "value", to benefit from consistent validation.

Leave a comment