How do I serve CSS to Django in development?

后端 未结 4 1427
心在旅途
心在旅途 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:34

    Here's how mine is setup. It sounds like you might be missing the static context processor?

    STATIC_ROOT and STATIC_URL

    In the settings.py used in development:

    STATIC_ROOT = ''
    STATIC_URL = '/static/'
    

    And the settings.py used on my production server:

    STATIC_URL = '//static.MYDOMAIN.com/'
    STATIC_ROOT = '/home/USER/public_html/static.MYDOMAIN.com/'
    

    So, all the static files are located in static/. On the production server, all these files in static/ are collected to /home/USER/public_html/static.MYDOMAIN.com/ where they are served by a different web server (nginx in my case) and not Django. In other words, my django application (running on Apache) never even receives requests for static assets in production.

    CONTEXT PROCESSOR

    In order for templates to have the STATIC_URL variable available to them, you need to use the django.core.context_processors.static context processor, also defined in settings.py:

    TEMPLATE_CONTEXT_PROCESSORS = (
        # other context processors....
        'django.core.context_processors.static',
        # other context processors....
    )
    

    SERVER STATIC ASSETS IN DEVELOPMENT

    Django doesn't get requests for static assets in production, however, in development we just let Django serve our static content. We use staticfiles_urlpatterns in urls.py to tell Django to serve requests for static/*.

    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    # .... your url patterns are here ...
    urlpatterns += staticfiles_urlpatterns()
    

提交回复
热议问题