Static files are not loaded in Django

后端 未结 2 1223
醉梦人生
醉梦人生 2021-01-27 03:30

I\'m trying to follow these instructions to enable static files in my Django project. I have

STATIC_URL = \'/static/\'

in my settings.py file.

相关标签:
2条回答
  • 2021-01-27 04:12

    In settings.py include this:

    import os
    settings_dir = os.path.dirname(__file__)
    PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
    
    STATICFILES_DIRS = (
        os.path.join(PROJECT_ROOT, 'static/mysite/'),
    )
    

    And in your urls.py include these lines at the end:

    from django.conf.urls.static import static
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    urlpatterns += staticfiles_urlpatterns()
    

    Hope it helps.

    0 讨论(0)
  • 2021-01-27 04:14

    I can suggest a couple things to check:

    • In my projects at least, the static folder is in the app directory, not the project directory. For example, mysite/myapp/static/myapp/img.jpg rather than mysite/static/mysite/img.jpg. Your project might not be looking in the right place.

    • Make sure that {% load staticfiles %} is in your html template before linking the files.

    • When you link a file in your html template, rather than direct urls like

    <link rel="stylesheet" href="myapp/css/custom.css">

    use

    <link rel="stylesheet" href="{% static 'myapp/css/custom.css' %}">

    This was enough to get static files working in my projects, without having to modify urls.py or manually set PROJECT_ROOT or STATICFILES_DIRS.

    0 讨论(0)
提交回复
热议问题