【发布时间】:2020-07-31 18:30:16
【问题描述】:
我是 Django 的初学者,正在尝试制作一个表格,该表格从 Django 数据库中获取数据(包含图像)。在 Django 模型中添加图像字段之前,这里一切正常。但我无法从 Django 媒体文件中获取图像(我还上传了具有超级用户和 Django 表单的图像,并且它们工作得很好)。下面是我的方法-
在 views.py 中:
def index(request):
table_data = TableA.objects.order_by('roll')
index_dict = {'insert_me' : "hello this is from views.py",
'dynamic_table' : table_data,
}
return render(request, 'app26/index.html', context=index_dict)
在HTML中:
{% if dynamic_table %}
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>Roll</th>
<th>Email</th>
<th>Password</th>
<th>Address</th>
<th>Profile Pic</th>
</tr>
</thead>
<tbody>
{% for i in dynamic_table %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.roll }}</td>
<td>{{ i.email }}</td>
<td>{{ i.password }}</td>
<td>{{ i.address }}</td>
<td><img class="profile-pic" src="{{media_url}}{{ i.profile_pic }}" alt=""></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>sorry cannot load the data for technical error</p>
{% endif %}
在 urls.py
中from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
我还设置了 MEDIA_URL 和 MEDIA_ROOT。从管理员我可以上传图片,它们没问题。 在 settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'Media')
MEDIA_URL = '/images/'
现在我的问题是表格的个人资料图片列中没有显示任何内容,甚至没有显示任何错误。 请建议我如何从数据库中获取图像文件以供我使用
【问题讨论】:
标签: django-media