猿问

如何在 Django 模板中使用 Bootstrap/static 文件

好吧,我知道有很多关于这个的问题,我已经梳理了所有这些问题,试图找到答案,但没有什么是我正在寻找的。


我的问题是,每当我尝试将静态文件加载到 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')

]

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


def home(request):

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

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

<!DOCTYPE html>

<html>


{% 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>


aluckdog
浏览 134回答 1
1回答

qq_笑_17

原来pycharm搞砸了。我上传了一个免费的 Bootstrap 模板并使用了相同的方法:&nbsp;{% static load %}在我的 html 文件中。pycharm 再次突出显示了所有有href="{%static ...directory... %}"错误的 html,但是当我启动服务器时,模板及其所有 css 都显示为正常,所以 pycharm 在这种情况下表现得很奇怪。
随时随地看视频慕课网APP

相关分类

Python
我要回答