How do I serve CSS to Django in development?

后端 未结 4 1428
心在旅途
心在旅途 2021-02-02 03:37

I\'ve been all through the documentation, and it just doesn\'t make sense to me. I ran collectstatic, I set up /static/ directories in both my app and my project directories, I

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 04:30

    The idea behind the static files idea is that you can distribute your development related media file (css/js etc.) on a per-app basis, and allow the static files application to manage and collect all these resources from their various places.

    So you tell the static files app where to look for static files (by settings STATICFILES_DIRS), where to copy to them (STATIC_ROOT) and what path to access them (STATIC_URL). When you run collectstatic, it search through the directories and copies all the files it finds into the static root.

    The benefit of this is that you can manage your static files on a finer leve:

    project/app1/static/css/ # These are css/js for a particular app
    project/app2/static/css/
    project/app3/static/css/
    project/static/css # These might be general css/js for the whole project
    static/ # This is where the collectstatic command will copy files to
    

    and after you collectstatic them you will have:

    project/app1/static/css/
    project/app2/static/css/
    project/app3/static/css/
    project/static/css
    
    static/app1/css/
    static/app2/css/
    static/app3/css/
    static/css/
    

    When you put your app/site on a production server, you let the webserver (apache, nginx) deal with serving the files by telling it to serve media files at /static/ or /media/ directly, while passing all other requests to the application. When developing though, it's easier to let the development server do this for you.

    To do this, you have explicitly tell is server any request for media under /static/ (your STATIC_URL). In your urls.py, put the following (or similar)

    from django.conf import settings
    ...
    if settings.DEBUG:
        urlpatterns += patterns('',
            url(r'^media/(?P.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),
            url(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True }))
    

提交回复
热议问题