Reputation: 10765
what is the best way to validate JSON data in Django/python.
Is it best to create a bunch of classes like the Django FormMixin classes that can validate the data/ parameters being passed in?
What's the best DRY way of doing this? Are there existing apps that I can leverage?
I'd like to take in JSON data and perform some actions/ updates to my model instances as a result. The data I'm taking in is not user generated - that is they are id's and flags (no text) so I don't want to use Forms.
Upvotes: 4
Views: 6295
Reputation: 259
I would recommend a python library named DictShield for this https://github.com/j2labs/dictshield
DictShield is a database-agnostic modeling system. It provides a way to model, validate and reshape data easily.
There is even a sample for doing JSON validation:
Validating User Input
Let's say we get this JSON string from a user.
{"bio": "Python, Erlang and guitars!", "secret": "e8b5d682452313a6142c10b045a9a135", "name": "J2D2"}
We might write some server code that looks like this:
json_string = request.get_arg('data')
user_input = json.loads(json_string)
user.validate(**user_input)
Upvotes: 1
Reputation: 5303
validictory validates json to a json-schema. It works. Of course, now you need to define your schema in json which may be a little much for what you want to do, but it does have it's place.
Upvotes: 4
Reputation: 92569
I just instantiate a model object from the json data and call full_clean() on the model to validate: https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean
m = myModel(**jsondata)
m.full_clean()
Upvotes: 7