Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for architecturing data validation in a Django multi sided project [closed]

I know it's a broad question. But let's imagine you have a Django project with an API used by mobile app clients.

There are many places where you can add validation logic:

  • Models fields themselves
  • Models, by overriding save() method
  • Django forms and model forms.
  • API Serializers (generic serializers or model serializers)

When architecturing your project, what rules/elements help you to choose whether validation should be put here or there?

like image 612
David D. Avatar asked Feb 11 '16 11:02

David D.


1 Answers

This is an opinion and style question. I think that that models validation is an absolute requirement, the last defence line against mistakes. Once models validations are in place, you can go on with forms, client and API facing validation.

The specific model validation, fields or model methods (or custom managers etc) is a choice of style, and what works for the specific app, but keep models validation. It's the one place to catch it all. You may have many forms, many APIs, but one point where data goes into the DB.

One of django advantages is that in many cases models validation propagates, e.g. ModelForms. So it's also a convenience, but this is a nice to have: models validation is essentially the last gate to the DB and should be treated properly.

Side note: "fields" validation is actually "DB validation", and "django field validation".

To keep with the DRY principle as much as possible:

  1. Use the django approach of generic validators. So even if you validate in several places, you use the same validation. If this validation changes, it changes everywhere, see https://docs.djangoproject.com/en/1.9/ref/validators/

  2. When possible, all client facing objects should pull the model validations, and use them, or map them to the correct client side validation, similarly to ModelForms.

  3. When possible, use the model validations error messages to create a meaningful feedback to client.

But validations may repeat steps after all, mainly because validation has (at least) two roles: clean the data, and provide feedback to user. The best example is client side validation. It's useful to provide immediate feedback,w/o roundtrip to the server, but it repeats the server side validation. The model validation just makes sure that as you add more forms, API, options, if you forget to implement the correct validation - the model will prevent it.

like image 189
Aviah Laor Avatar answered Sep 23 '22 12:09

Aviah Laor