我正在学习编写一个 Django 应用程序,它将从 os.path.join(BASE_DIR, 'media_root', 'uploads') 获取所有图像并将其显示在 html 页面上。
但它不是这样工作的。
管理员.py
from .models import Experience
# Register your models here.
admin.site.register(Experience)
设置.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
MEDIA_URL = '/media/'
模型.py
class Experience(models.Model):
id = models.AutoField(primary_key=True)
image = models.ImageField(upload_to='uploads/', default='newbalance.jpg', height_field=None, width_field=None)
studio_name = models.CharField(max_length=255)
designation = models.CharField(max_length=255)
duration = models.CharField(max_length=255)
description_short = models.TextField()
description_long = models.TextField()
keywords = models.CharField(max_length=255)
date = models.DateTimeField('DateAdded',
auto_now=True, auto_now_add=False)
class Meta:
db_table = "experience"
def __str__(self):
return self.studio_name + ' ' + self.duration
视图.py
class ExperienceList(generic.ListView):
model = Experience
template_name = 'resumesection.html'
queryset = Experience.objects.all()
网址.py
urlpatterns = [
path('modelview/', views.ExperienceList.as_view(), name='experience_list'),
]
在错误日志中,
2021-07-19 04:15:40,528: Not Found: /resume_site/modelview/uploads/atomic_arts.png
2021-07-19 04:15:41,239: Not Found: /resume_site/modelview/uploads/futureworks.jpg
我认为 django 应该从“MEDIA_ROOT/uploads”文件夹中读取图像,但它是从“/resume_site/modelview/uploads/”中读取的。哪个不存在。
我在这篇文章Django admin view uploaded photo中接近了答案,但无法连接 'MEDIA_ROOT/uploads' 和 '/resume_site/modelview/uploads/' 之间的点
查看从管理员上传的图像如何在 django 中工作。?
编辑:上下文中 resumesection.html 的一部分
{% for exp in object_list %}
<h5>{{exp.studio_name}} | {{exp.duration}}</h5>
<img src="{{exp.image}}">
<p id="description_short_text">
{{exp.description_short}}
</p>
<p id="text" style="display:none;color:red">
{{exp.description_long}}
</p>
<h4 id='keywords_text' style="display:block;color:green">KEYWORDS</h4>
<p id='alt_text' style="display:block;color:green">{{exp.keywords}}</p>
{% endfor %}
项目中的 urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('barefoot/', include('barefoot.urls')),
path('resume_site/', include('resume_site.urls')),
path('photo_gallery/', include('photo_gallery.urls')),
]
if settings.DEBUG: # added
import debug_toolbar
urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)