﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
30840	Sending JSON using the django test client fails when providing content_type='application/json'	Fernando Cordeiro	nobody	"Given the following statement from the docs (https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.Client.post):
 If you provide content_type as application/json, the data is serialized using json.dumps() if it’s a dict, list, or tuple.

I created the following TestCase in order to test if my AJAX POST request could update my model correctly:

{{{
class MyUpdateViewTest(TestCase):

    def test_update_model_field(self):
        self.client.force_login(self.user)
        url = reverse('MyModel_update', args=[pk])
        resp = self.client.post(
            url,
            data={'field' : 4},
            content_type='application/json',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest'
        )
        obj = MyModel.objects.filter(...)
        self.assertEqual(obj[0].field, 4)
}}}

The corresponding view:

{{{
class MyUpdateView(UpdateView):
    """"""Updates a MyModel via its pk with AJAX form data""""""
    model = MyModel
    form_class = MyModelForm

    def form_valid(self, form):
        self.object = form.save()
        data = {'pk': self.object.pk}
        return JsonResponse(data)

    def form_invalid(self, form):
        return JsonResponse(form.errors, status=400)

    def post(self, request, *args, **kwargs):
        if request.is_ajax():
            return super().post(self, request, *args, **kwargs)
        else:
            return HttpResponseBadRequest()
}}}

What happened was that whenever I added `content_type='application/json'`, the view never received any data at all (i.e. request.POST was an empty queryset) which then made the `form.is_valid()` method fail and return a form field error. I tried this with and without ´json.dumps()` on the POST data.

However, as soon as I removed the `content_type='application/json'` parameter, the test worked! So, given the docs, I believe a bug is afoot.

This problem only happened during testing."	Bug	closed	Testing framework	2.2	Normal	invalid	ajax		Unreviewed	0	0	0	0	0	0
