From eeed488a3439c5c5c3f0b5991ee400851057e127 Mon Sep 17 00:00:00 2001 From: Alex Hayward Date: Wed, 19 May 2021 12:19:23 +0100 Subject: [PATCH] Fixed #32768 -- Added Vary header when redirecting to prefixed i18n pattern. get_language_from_request() uses Accept-Language and/or Cookie to determine the correct redirect. Upstream caches need the matching Vary header to cache the result. --- django/middleware/locale.py | 7 ++++++- tests/i18n/patterns/tests.py | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/django/middleware/locale.py b/django/middleware/locale.py index 0bbdda3309..d90fc84152 100644 --- a/django/middleware/locale.py +++ b/django/middleware/locale.py @@ -53,7 +53,12 @@ class LocaleMiddleware(MiddlewareMixin): '%s%s/' % (script_prefix, language), 1 ) - return self.response_redirect_class(language_url) + # Redirect to the language-specific URL as detected by + # get_language_from_request(). HTTP caches may cache this + # redirect, so add the Vary header. + redirect = self.response_redirect_class(language_url) + patch_vary_headers(redirect, ('Accept-Language', 'Cookie')) + return redirect if not (i18n_patterns_used and language_from_path): patch_vary_headers(response, ('Accept-Language',)) diff --git a/tests/i18n/patterns/tests.py b/tests/i18n/patterns/tests.py index 96e9453e9e..ebd2430428 100644 --- a/tests/i18n/patterns/tests.py +++ b/tests/i18n/patterns/tests.py @@ -254,9 +254,13 @@ class URLVaryAcceptLanguageTests(URLTestCaseBase): self.assertEqual(response.get('Vary'), 'Accept-Language') def test_en_redirect(self): + """ + The redirect to a prefixed URL depends on 'Accept-Language' and + 'Cookie', but once prefixed no header is set. + """ response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='en') self.assertRedirects(response, '/en/account/register/') - self.assertFalse(response.get('Vary')) + self.assertEqual(response.get('Vary'), 'Accept-Language, Cookie') response = self.client.get(response.headers['location']) self.assertEqual(response.status_code, 200)