英文:
How to Loading Static Files in Django Template?
问题
问题描述:
我正在尝试在我的Django项目中设置一个目录结构,其中static
文件夹位于user
文件夹内,而user
文件夹又位于templates
文件夹内。我的意图是让静态文件靠近模板文件。然而,我在让Django从这个目录结构中正确提供静态文件方面遇到了困难。
目录结构:
project/
├── templates/
│ └── user/
│ ├── index.html
│ └── static/
│ └── css/
│ └── main.css
└── ...
其他细节:
- 我在
settings.py
中配置了STATIC_URL
:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'/static/')]
STATIC_ROOT = os.path.join(BASE_DIR, "/static")
- 在我的
index.html
文件中,我使用<link rel="stylesheet" href="{% static 'css/main.css' %}">
标签来引用静态文件。
遇到的问题:
尽管调整了设置,但我仍然无法使Django从这个特定的目录结构中正确提供静态文件。我尝试了不同的配置,比如更改STATIC_URL
,但仍然没有成功。非常感谢任何帮助。
英文:
Problem Description:
I'm trying to set up a directory structure in my Django project where the static
folder is inside the user
folder, which is in turn inside the templates
folder. My intention is to have static files located close to the template files. However, I'm having difficulties getting Django to properly serve static files from this directory structure.
Directory Structure:
project/
├── templates/
│ └── user/
│ ├── index.html
│ └── static/
│ └── css/
│ └── main.css
└── ...
Additional Details:
- I've configured
STATIC_URL
insettings.py
:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'/static/')]
STATIC_ROOT = os.path.join(BASE_DIR, "/static")
- In my
index.html
file, I'm using the<link rel="stylesheet" href="{% static 'css/main.css' %}">
tag to reference static files.
Issue Faced:
Despite adjusting the settings, I'm unable to make Django serve static files properly from this specific directory structure. I've tried different configurations, such as changing STATIC_URL
, but I still haven't succeeded. Any help would be greatly appreciated.
答案1
得分: 1
解决方案:
-
更新
STATICFILES_DIRS
: 在settings.py
文件中,用户最初使用路径'C:/user/templates/user/static'
配置了STATICFILES_DIRS
。然而,这个路径结构是不正确的。 -
移除前导斜杠: 用户在
os.path.join
调用中移除了'user/templates/user/static'
之前的前导斜杠,以建立正确的路径。STATICFILES_DIRS = [os.path.join(BASE_DIR, 'user/templates/user/static')]
-
使用正斜杠: 用户确保在目录路径中使用正斜杠
/
,即使在Windows系统上也是如此,因为Python和Django在内部处理路径转换。 -
重新启动服务器: 应用这些更改后,用户重新启动了Django开发服务器以生效配置。
英文:
Solution:
-
Updating
STATICFILES_DIRS
: In thesettings.py
file, the user had initially configuredSTATICFILES_DIRS
with the path'C:/user/templates/user/static'
. However, this path structure was incorrect. -
Removing Leading Slash: The user removed the leading slash before
'user/templates/user/static'
in theos.path.join
call to establish a proper path.STATICFILES_DIRS = [os.path.join(BASE_DIR, 'user/templates/user/static')]
-
Using Forward Slashes: The user ensured the use of forward slashes
/
in the directory path, even on Windows systems, as Python and Django internally handle path conversions. -
Restarting Server: After applying these changes, the user restarted the Django development server to enact the configuration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论