When my page POSTs a form to my Django view, the view returns a response with some data but soon I ran into the issue that my views returned data in different formats and different sets of information. I’ve thought of using JSON as a standard format to return my data.
There are two types of statuses, success and failure. When the POST was successful, it just returns success but when it has failed, it returns a sub group called errors which contains a of fields and that field’s error.
Here’s a sample failure response:
{"failure": {
"errors":[
{"fieldname": "<fieldname>",
"fielderror": "<fielderror>"
},
{"fieldname": "<fieldname>",
"fielderror": "<fielderror>"
}]
}}
Here’s a sample success response:
{"success": {
"data":[
{"fieldname": "<fieldname>",
"fielddata": "<fielddata>"
},
{"fieldname": "<fieldname>",
"fielddata": "<fielddata>"
}]
}}
(The success response has data fields because quite often you like to return some data i.e. key of newly created DB record.)
This is what I’ve come up with but so many people using Django out there, I’m wondering whether there is a standard way/more robust of doing this or some module to help with this.
Thanks.
been there. I wrote the solution my own (since it’s simple. I dont know if theres a module out there for this). This is just a json response wrapper
something like that. In my case, I make
SuccessandFailureaccept a string and a dictionary for arguments (likeSuccess(data)) to make it even easierIf your structure is quite complex (or youre too lazy too write them manually), write your own wrapper for that complicated structure (so you can create the response with even less typing), and make the Success/Failure accepts that as argument.