在 Web 应用程序中,除了业务逻辑和数据处理之外,我们还需要处理和管理 CSS、JavaScript、图像等静态资源。
管理这些资源很重要,以免影响我们的应用程序性能。 Django 非常高效地处理它,并提供了一种方便的资源使用方式。
要提供静态文件,请遵循以下步骤。
在 settings.py 中添加以下内容
settings.py
#STATIC_URL: specifies what to append when you call `{% static %}` as template tag.
STATIC_URL = '/static/'
#STATIC_ROOT: specifies where exactly you yourself will put your static files
STATIC_ROOT = os.path.join(BASE_DIR, 'staticroot')
#STATICFILES_DIRS: it tells Django where to look for static files while
#serving a request.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
之后在项目的根目录下创建一个staticroot 目录。然后把你所有的javascript,css,images放在那里并运行以下命令。
python manage.py collectstatic
此命令会将所有文件收集到/static/ 文件夹中。
现在在开发过程中为您的静态文件添加以下内容到您的主 urls.py
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# Your URL configs
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
之后,您可以在任何地方使用您的静态文件。
例如:您需要在模板中添加背景图片,您应该添加以下代码
template.html
<!--{% load static %} should be always top of your template file. It tells
Django to load your static files inside template. -->
{% load static %}
<!--{% static 'resource_url' %} means STATIC_URL+'resource_url'. (STATIC_URL
defined inside your settings.py) -->
<img src="{% static "my_app/example.jpg" %}" alt="My image">
这应该可以解决您的问题。