From a3a4f5c1447b10cee63d9fee518d0d6b5b881846 Mon Sep 17 00:00:00 2001 From: Troon Date: Thu, 9 May 2019 15:26:52 +0100 Subject: [PATCH] Fixed #30310 -- Added support for looking up HttpHeaders.headers using underscores. --- django/http/request.py | 4 ++++ docs/ref/request-response.txt | 9 +++++++++ docs/releases/3.0.txt | 3 +++ tests/requests/tests.py | 1 + 4 files changed, 17 insertions(+) diff --git a/django/http/request.py b/django/http/request.py index 1e1cc6c397..e62e2272b2 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -369,6 +369,10 @@ class HttpHeaders(CaseInsensitiveMapping): headers[name] = value super().__init__(headers) + def __getitem__(self, key): + """Allow header lookup using underscores in place of hyphens.""" + return super().__getitem__(key.replace('_', '-')) + @classmethod def parse_header_name(cls, header): if header.startswith(cls.HTTP_PREFIX): diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt index d6a336178e..58a7c3e7e4 100644 --- a/docs/ref/request-response.txt +++ b/docs/ref/request-response.txt @@ -199,6 +199,15 @@ All attributes should be considered read-only, unless stated otherwise. >>> request.headers.get('user-agent') Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) + For use in, for example, Django templates, headers can also be looked up + using underscores in place of hyphens:: + + {{ request.headers.user_agent }} + + .. versionchanged:: 3.0 + + Support for look ups using underscores was added. + .. attribute:: HttpRequest.resolver_match An instance of :class:`~django.urls.ResolverMatch` representing the diff --git a/docs/releases/3.0.txt b/docs/releases/3.0.txt index 335ab2c0d5..daf1ef513b 100644 --- a/docs/releases/3.0.txt +++ b/docs/releases/3.0.txt @@ -217,6 +217,9 @@ Requests and Responses * Allowed :class:`~django.http.HttpResponse` to be initialized with :class:`memoryview` content. +* For use in, for example, Django templates, :attr:`.HttpRequest.headers` now + allows look ups using underscores (e.g. ``user_agent``) in place of hyphens. + Serialization ~~~~~~~~~~~~~ diff --git a/tests/requests/tests.py b/tests/requests/tests.py index a97b98e8a2..0c68105bb4 100644 --- a/tests/requests/tests.py +++ b/tests/requests/tests.py @@ -896,6 +896,7 @@ class RequestHeadersTests(SimpleTestCase): request = WSGIRequest(self.ENVIRON) self.assertEqual(request.headers['User-Agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['user-agent'], 'python-requests/1.2.0') + self.assertEqual(request.headers['user_agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['Content-Type'], 'text/html') self.assertEqual(request.headers['Content-Length'], '100')