[Solved]-Django dev server, adding headers to static files

6👍

staticfiles app overrides the core runserver command but allows you to disable the automatic serving of the static files:

python manage.py runserver --nostatic

0👍

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
    )

Leave a comment