From cbcdabf8446c6cd43e6f212c5a3c1dbd52342477 Mon Sep 17 00:00:00 2001 From: David Evans Date: Tue, 28 Jul 2020 10:41:06 +0100 Subject: [PATCH] Ensure relative STATIC_URLs are supported This is a new feature added in Django 3.1. We now use the `get_script_prefix` function rather than the `FORCE_SCRIPT_NAME` setting so we handle the case where the script prefix is supplied from the webserver rather than from settings. --- tests/test_django_whitenoise.py | 9 +++++++++ whitenoise/middleware.py | 9 +++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/tests/test_django_whitenoise.py b/tests/test_django_whitenoise.py index 94535aa0..1be6c7ab 100644 --- a/tests/test_django_whitenoise.py +++ b/tests/test_django_whitenoise.py @@ -209,3 +209,12 @@ def test_whitenoise_file_response_has_only_one_header(): # This subclass should have none of the default headers that FileReponse # sets assert headers == {"content-type"} + + +@pytest.mark.skipif(django.VERSION[:2] < (3, 1), reason="feature added in Django 3.1") +@override_settings() +def test_relative_static_url(server, static_files, _collect_static): + settings.STATIC_URL = "static/" + url = storage.staticfiles_storage.url(static_files.js_path) + response = server.get(url) + assert response.content == static_files.js_content diff --git a/whitenoise/middleware.py b/whitenoise/middleware.py index e8f5a87a..feec8a31 100644 --- a/whitenoise/middleware.py +++ b/whitenoise/middleware.py @@ -6,6 +6,7 @@ from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.staticfiles import finders from django.http import FileResponse +from django.urls import get_script_prefix from .base import WhiteNoise from .string_utils import decode_if_byte_string, ensure_leading_trailing_slash @@ -82,10 +83,10 @@ def configure_from_settings(self, settings): self.autorefresh = settings.DEBUG self.use_finders = settings.DEBUG self.static_prefix = urlparse(settings.STATIC_URL or "").path - if settings.FORCE_SCRIPT_NAME: - script_name = settings.FORCE_SCRIPT_NAME.rstrip("/") - if self.static_prefix.startswith(script_name): - self.static_prefix = self.static_prefix[len(script_name) :] + script_prefix = get_script_prefix().rstrip("/") + if script_prefix: + if self.static_prefix.startswith(script_prefix): + self.static_prefix = self.static_prefix[len(script_prefix) :] if settings.DEBUG: self.max_age = 0 # Allow settings to override default attributes