From 79f3de95325d126ee14f0a696069c7a4881c5f3e Mon Sep 17 00:00:00 2001 From: Adam Ness Date: Mon, 2 Jul 2012 20:00:07 -0700 Subject: [PATCH] Patch to enable Accept headers in Internet Explorer when an Ajax Library on the client (i.e. jQuery) is sending an XMLHttpRequest --- djangorestframework/response.py | 3 ++- djangorestframework/tests/accept.py | 13 ++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/djangorestframework/response.py b/djangorestframework/response.py index ea9a938c6..0f12e99c1 100644 --- a/djangorestframework/response.py +++ b/djangorestframework/response.py @@ -110,7 +110,8 @@ class Response(SimpleTemplateResponse): return [request.GET.get(self._ACCEPT_QUERY_PARAM)] elif (self._IGNORE_IE_ACCEPT_HEADER and 'HTTP_USER_AGENT' in request.META and - MSIE_USER_AGENT_REGEX.match(request.META['HTTP_USER_AGENT'])): + MSIE_USER_AGENT_REGEX.match(request.META['HTTP_USER_AGENT']) and + request.META.get('HTTP_X_REQUESTED_WITH', '') != 'XMLHttpRequest'): # Ignore MSIE's broken accept behavior and do something sensible instead return ['text/html', '*/*'] elif 'HTTP_ACCEPT' in request.META: diff --git a/djangorestframework/tests/accept.py b/djangorestframework/tests/accept.py index 933854938..69bca707b 100644 --- a/djangorestframework/tests/accept.py +++ b/djangorestframework/tests/accept.py @@ -53,7 +53,18 @@ class UserAgentMungingTest(TestCase): resp = self.view(req) resp.render() self.assertEqual(resp['Content-Type'], 'text/html') - + + def test_dont_munge_msie_with_x_requested_with_header(self): + """Send MSIE user agent strings, and an X-Requested-With header, and + ensure that we get a JSON response if we set a */* Accept header.""" + for user_agent in (MSIE_9_USER_AGENT, + MSIE_8_USER_AGENT, + MSIE_7_USER_AGENT): + req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent, HTTP_X_REQUESTED_WITH='XMLHttpRequest') + resp = self.view(req) + resp.render() + self.assertEqual(resp['Content-Type'], 'application/json') + def test_dont_rewrite_msie_accept_header(self): """Turn off _IGNORE_IE_ACCEPT_HEADER, send MSIE user agent strings and ensure that we get a JSON response if we set a */* accept header."""