【问题标题】:django tutorial, not loading my static files properlydjango 教程,没有正确加载我的静态文件
【发布时间】:2020-04-01 13:42:52
【问题描述】:

这是我的错,我正在学习不同的教程,但第一个教程效果很好,我想我会遵循更详细的教程。无论如何,第一个让我将模板文件夹移到博客应用程序之外并将其移动到路由,所以我在设置上有以下内容:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

该教程的问题,它不包括任何 css 的静态设置以及我需要的任何静态文件。也就是说,我正在关注另一个教程,让我像这样放置 css

|- blog
|---static
|-----blog
|-------main.css
|- django_app
|---all the settings found here
|- templates
|---blog
|-----all my templates are here

并将其放在模板的 base.html 上

<style rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"></style>

但我的模板没有找到它。我能够通过以下 url 跟踪我的 css

http://127.0.0.1:8000/static/blog/main.css

我知道 django 的最佳实践是什么以及它的文件夹结构,但任何建议都值得赞赏。谢谢

【问题讨论】:

  • 你应该在settings.py中设置STATIC_ROOTSTATIC_URL。关注这个link
  • 如果我错了,请纠正我,但 static_root 仅在部署正确时使用?我仍然在我的本地,并且 static_url 已经在那里,我还放置了链接上提到的 STATICFILES_DIRS。还在 blog.urls "+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)" 上添加了这些,不知道我还缺少什么
  • 你能cd 进入你的project directory 并运行tree 并向我们展示你的项目结构的输出吗?你给的那个很难理解也很难帮助你

标签: django django-views django-templates


【解决方案1】:

这纯粹是我的建议,可能有更好的方法。

settings.py

​​>
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'

文件夹结构

├───django_app
└───blog
    ├───static
    │   ├───css    // folder for css files
    │   ├───img    // folder for image files
    │   └───js     // folder for javascript files
    └───templates
        └───blog   // html files for blog app

HTML 页面

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2018-10-07
    • 2020-09-11
    • 2017-12-06
    • 2020-11-04
    • 2019-12-30
    • 2021-09-04
    相关资源
    最近更新 更多