Using the django dev server (1.7.4), I want to add some headers to all the static files it serves.
It looks like I can pass a custom view to django.conf.urls.s
I found the code of the author did not work for me, I would get errors like:
[10/Dec/2020 18:08:13] "GET /static/img/foo.svg HTTP/1.1" 404 10482
Not Found: /static/img/foo.svg
I am using Django 3 if that makes a difference.
This is what I did:
from django.contrib.staticfiles.views import serve
def custom_serve(request, path, insecure=False, **kwargs):
"""
Customize the response of serving static files.
Note:
This should only ever be used in development, and never in production.
"""
response = serve(request, path, insecure=True)
response['Access-Control-Allow-Origin'] = '*'
# if path.endswith('sw.js'):
# response['Service-Worker-Allowed'] = '/'
return response
the urls part is the same as the question:
from django.conf import settings
if settings.DEBUG:
# Allow custom static file serving (use with manage.py --nostatic)
from django.conf.urls.static import static
from CHANGE.THIS.PATH.views import custom_serve
urlpatterns += static(
settings.STATIC_URL, document_root=settings.STATIC_ROOT, view=custom_serve
)