在Django中加载静态文件

问题描述 投票:0回答:1

我尝试了大约2个小时来弄清楚为什么我的django静态文件没有加载。这是我在settings.py中的静态文件配置:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

这是我的base.py的一部分:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}">
<link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css'%}%">

这是我的目录树:

D:.
├───.vscode
├───blog
│   ├───migrations
│   │   └───__pycache__
│   └───__pycache__
├───courses
│   ├───migrations
│   │   └───__pycache__
│   └───__pycache__
├───lingua
├───main
│   ├───migrations
│   │   └───__pycache__
│   └───__pycache__
├───pia
│   └───__pycache__
├───posts
│   ├───migrations
│   │   └───__pycache__
│   └───__pycache__
├───static
│   ├───admin
│   │   ├───css
│   │   │   └───vendor
│   │   │       └───select2
│   │   ├───fonts
│   │   ├───img
│   │   │   └───gis
│   │   └───js
│   │       ├───admin
│   │       └───vendor
│   │           ├───jquery
│   │           ├───select2
│   │           │   └───i18n
│   │           └───xregexp
│   ├───images
│   ├───js
│   ├───plugins
│   │   ├───easing
│   │   ├───font-awesome-4.7.0
│   │   │   ├───css
│   │   │   ├───fonts
│   │   │   ├───less
│   │   │   └───scss
│   │   ├───OwlCarousel2-2.2.1
│   │   ├───parallax-js-master
│   │   ├───progressbar
│   │   └───video-js
│   └───styles
│       └───bootstrap4
├───static_in_env
└───templates
    ├───blog
    ├───courses
    ├───main
    └───posts

你能帮我弄清楚为什么静态文件不起作用。

css django
1个回答
0
投票

你的STATICFILES_DIR看起来不对劲。

试试这个:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
YOURAPP_DIR = os.path.join(BASE_DIR, 'yourapp')

STATIC_URL = '/static/' 

STATICFILES_DIR = [
    os.path.join(YOURAPP_DIR, 'static')
]

其中yourapp是您的应用程序的名称(而不是您的项目)。

现在,在您的模板上,您可以像这样访问它们:

{% load static %}

<link src="{% static 'someFile.css' %}">

如果css文件夹中有一个名为static的文件夹,则可以访问该文件夹中的文件,如下所示:

<link src="{% static 'css/someFile.css' %}">
© www.soinside.com 2019 - 2024. All rights reserved.