【问题标题】:How to use Bootstrap/static files in Django templates如何在 Django 模板中使用 Bootstrap/静态文件
【发布时间】:2020-11-13 15:35:35
【问题描述】:

好的,所以我知道有很多关于此的 SO 问题,我已经梳理了所有这些问题,试图找到答案,但没有什么是我想要的。

我的问题是,每当我尝试将静态文件加载到 Django 模板中时,它都无法正常工作。 这是我的文件结构:

MainProjectDir
|
+-- DjangoProject
|  |
|  +-- MainDjangoSub
|  |  |
|  |  +-- __init__.py
|  |  +-- settings.py (all the other usual folders below)
|  |
|  +-- StaticPages (this is my App directory)
|  |  |
|  |  +-- templates (will contain all templates for StaticPages app)
|  |  |  |
|  |  |  +-- StaticPages (directory containing html templates for the Static Pages App)
|  |  |  |  |
|  |  |  |  +-- main.html
|  |  |  |  +-- navbar.html
|  |  |
|  |  +-- __init__.py
|  |  +-- views.py (all other usual app files below)
|  |
|  +-- static (contains all static files for the project)
|  |  |
|  |  +-- Bootstrap (subdirectory containing the Bootstrap static files)
|  |  |  |
|  |  |  +-- css (directory containing all css files from Bootstrap precompiled files)
|  |  |  +-- js (directory containing all js files from Bootstrap precompiled files)
|  +-- manage.py

我的设置文件中与静态文件有关的设置:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'StaticPages',
]

STATIC_URL = '/static/'


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

在我的静态页面应用程序下的 views.py 文件中,我有这个视图来呈现我的模板:

def home(request):
    return render(request, 'StaticPages/main.html')

所以我们来解决我的问题。在 main.html 文件中,我使用 {% load static %} 加载静态文件,然后在对 css 或 js 文件的任何调用中,我做了类似的事情,但 pycharm 突出显示文本并说“无法解析目录......”这是一个示例我的 html 文件:

<!DOCTYPE html>
<html lang="en">

{% load static %}

<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href='{% static "/Bootstrap/css/bootstrap.min.css" %}'
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <style>
        .navbar-custom{
            background-color: #e86813;
        }
    </style>

    <h3>Hello World</h3>

</head>
<body>
    {% include 'StaticPages/navbar.html' %}
</body>
</html>

【问题讨论】:

    标签: python html django twitter-bootstrap pycharm


    【解决方案1】:

    原来 pycharm 搞砸了。我上传了一个免费的 Bootstrap 模板并使用了相同的方法: {% static load %} 在我的 html 文件中。

    pycharm 再次突出显示了任何具有 href="{%static ...directory... %}" 的 html 并给出了错误,但是当我启动服务器时,模板及其所有 css 都正常显示,所以 pycharm 在这种情况下表现得很奇怪。

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2012-12-10
      • 2023-03-29
      • 2016-11-11
      • 1970-01-01
      • 2016-04-03
      • 2013-06-18
      • 1970-01-01
      • 2012-02-28
      相关资源
      最近更新 更多