Django 中的静态图像/媒体文件



我无法在我的模板中使用 Django 加载静态文件,我的文件如下所示

Settings.py

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

]

STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIR = [
STATIC_DIR,
]

Template/index.html

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First App</title>
</head>
<body>
<h1>Hello this is index.html!</h1>
<img src="{% static 'images/mark.jpg' %}" alt="My image">
</body>
</html>

项目故事

这是项目目录'

将这些代码也添加到您的主 url 文件中

if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

并在设置中添加此行

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")

STATICFILES_DIR列表应命名为STATICFILES_DIRS

在开发中,当您使用runserver运行并DEBUG=True就足够了。


要在生产中提供静态文件,请执行以下操作:

  • 建议使用外部 Web 服务器(在生产环境中,您很可能会在 Django 前面有一个或 Web 代理(。呼叫collectstatic并使用网络服务器提供结果static_root目录

  • 或者您可以将它们上传到CDN(AWS S3,CLoudflare(

  • 或者可以使用Whitenoise让django为它们服务

  • 最不推荐但仍然可能 - 通过添加静态 URL 与 Django 一起开发

相关内容

最新更新