我正在尝试在 DetailView 的模板上显示媒体文件(图像)。
我运行打印语句来检查 MEDIA_ROOT 和 MEDIAFILES_DIRS 指向的位置,它们都正确指向 /project/static/media。
所以我尝试通过使用在html页面上调用它<img src="{{ object.profile_pic.url }}" />
,但它没有显示。
我检查了控制台,它正在寻找 XXX.XXX:8000/media/image_file.jpg 中的文件。
这与我在 settings.py 中的媒体文件设置有关吗?
这就是我的文件夹结构的样子
/project
/project
/project
urls.py (base)
/apps
/app1
urls.py
manage.py
/static
/media
image_file.jpg
设置.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(os.path.dirname(BASE_DIR), "static", "static_files"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static_root")
"""
MEDIA FILES
"""
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
MEDIAFILES_DIRS = [
os.path.join(os.path.dirname(BASE_DIR), "static", "media"),
]
"""
Override the BaseUser model
"""
AUTH_USER_MODEL = 'accounts.User'
urls.py // 需要将 +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 添加到基本 urls.py,而不是应用级别
from django.conf.urls import include, url
from django.contrib import admin
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.HomepageTemplateView.as_view(), name='home'),
url(r'^how-it-works/$', views.HowItWorksTemplateView.as_view(), name='how-it-works'),
url(r'^categories/', include('apps.categories.urls')),
url(r'^tasks/', include('apps.tasks.urls')),
url(r'^accounts/', include('apps.accounts.urls')),
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
详细视图.html
{% extends 'base.html' %}
{% block navbar %}
<div class="row">
<div class="container">
{% include 'navbar.html' %}
</div>
</div>
{% endblock %}
{% block content %}
<div class="row">
<div class="container">
<div class="col-md-12">
{% load staticfiles %}
<p><img src="{{ object.profile_pic.url }}" /></p>
<p>{{ object.username }}</p>
<p>{{ object.first_name }} {{ object.last_name }}</p>
<p>{{ object.email }}</p>
<p>{{ object.contractorprofile.subcategory }}</p>
</div>
</div>
</div>
{% endblock %}