简体   繁体   English

静态文件未在Django中加载

[英]Static files are not loaded in Django

I'm trying to follow these instructions to enable static files in my Django project. 我正在尝试按照以下说明在Django项目中启用静态文件。 I have 我有

STATIC_URL = '/static/'

in my settings.py file. 在我的settings.py文件中。 I have 'django.contrib.staticfiles', added to the INSTALLED_APPS = (...) part I created a folder mysite/static/mysite and put my files there. 我有'django.contrib.staticfiles',添加到INSTALLED_APPS = (...)部分,我创建了一个文件夹mysite/static/mysite ,并将我的文件放在那里。 But after I run the server, I cannot access my files at http://127.0.0.1:8000/static/mysite/style.css . 但是运行服务器后,我无法访问http://127.0.0.1:8000/static/mysite/style.css文件。 What I have done wrong? 我做错了什么?

In settings.py include this: settings.py包括以下内容:

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: 并且在您的urls.py包括以下urls.py行:

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

Hope it helps. 希望能帮助到你。

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. 至少在我的项目中,静态文件夹位于app目录中,而不是项目目录中。 For example, mysite/myapp/static/myapp/img.jpg rather than mysite/static/mysite/img.jpg . 例如, mysite/myapp/static/myapp/img.jpg而不是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. 链接文件之前,请确保您的html模板中包含{%load staticfiles%}。

  • When you link a file in your html template, rather than direct urls like 当您在html模板中链接文件时,而不是直接链接

<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. 这足以使静态文件在我的项目中工作,而无需修改urls.py或手动设置PROJECT_ROOT或STATICFILES_DIRS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM