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



好吧,我知道这方面有很多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')
]

在StaticPages应用程序下的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>

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

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

最新更新