I’m converting some code that uses jQuery to post data to Django over to AngularJS. The POSTed data wasn’t coming across as expected.
By default AngularJS and jQuery use two different methods of packaging data. According what I’ve gleaned from googling:
- jQuery posts using a content type of application/x-www-form-urlencoded and serializes the data using the foo=bar&fuz=baz method.
- AngularJS posts using a content type of application/json and serializes the data in the body.
Because this is an Angular single-page application, rather than using Django’s templating, I’m making calls to a web-based API (implemented in Django). I use a simple helper class for the repetitive task of extracting POSTed data, converting it to Python objects, and validating it.
I made a simple change to this object, and voilà — Django started receiving AngularJS data.
# This function extracts the received data and
# returns it as a Python dict.
if ‘CONTENT_TYPE’ in request.META and request.META[‘CONTENT_TYPE’].startswith(‘application/json’):
elif request.method == ‘POST’:
If you wish to use Django’s unit testing to exercise this, use something like the following. Remember to send a JSON serialized string into post() as it will not do this for you.
from json import dumps
from django.test.client import Client
client = Client()
response = client.post(url, dumps(data), content_type=’application/json’)
- Fixed bug in sample code.
- Added unit testing example.