Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django dev server, adding headers to static files

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.static.static, like so:

if settings.DEBUG:
    from django.conf.urls.static import static
    from common.views.static import serve

    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL,
        document_root=settings.STATIC_ROOT, view=serve)

And common.views.static.serve looks like this:

from django.views.static import serve as static_serve

def serve(request, path, document_root=None, show_indexes=False):
    """
    An override to `django.views.static.serve` that will allow us to add our
    own headers for development.

    Like `django.views.static.serve`, this should only ever be used in
    development, and never in production.
    """
    response = static_serve(request, path, document_root=document_root,
        show_indexes=show_indexes)

    response['Access-Control-Allow-Origin'] = '*'
    return response

However, simply having django.contrib.staticfiles in INSTALLED_APPS adds the static urls automatically, and there doesn't seem to be a way to override them. Removing django.contrib.staticfiles from INSTALLED_APPS makes this work, however, if I do that, the staticfiles templatetags are no longer available.

How can I override the headers that are served for static files using the django development server?

like image 954
synic Avatar asked Feb 25 '15 16:02

synic


People also ask

Can Django serve static files?

Deployment. django.contrib.staticfiles provides a convenience management command for gathering static files in a single directory so you can serve them easily. This will copy all files from your static folders into the STATIC_ROOT directory. Use a web server of your choice to serve the files.

How do I use Collectstatic in Django?

Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT . In our case, we are telling Django that when we run python manage.py collectstatic , gather all static files into a folder called staticfiles in our project root directory.


1 Answers

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

python manage.py runserver --nostatic
like image 181
catavaran Avatar answered Oct 18 '22 14:10

catavaran