python - Django不在视图上显示图像
问题描述
这是我的看法:
当我检查元素时,它给出的图像源是:
127.0.0.1:8000/store/arm-list/apple.jpg
和 :
所以这里是我的代码:
urls.py:
urlpatterns = [
path('arm-list/', VechileListView.as_view(), name='arm-list'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
视图.py:
class VechileListView(ListView):
model = Vechile
template_name = 'store/arm_list.html'
context_object_name = 'arm'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['vendor'] = Vendor.objects.all()
return context
设置.py
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_ROOT = os.path.join(BASE_DIR, 'store/images')
MEDIA_URL = '/media/'
模型.py
enter code here
class Vechile(models.Model):
no_polisi = models.CharField(max_length=10)
alias = models.CharField(max_length=20, null=True)
photo = models.ImageField(upload_to='', null=True)
....
arm_list.html
enter code here
{% if arm %}
{% for arm in arm %}
<tr>
<td class="serial">{{ forloop.counter }}</td>
<td><img src="{{ arm.photo.url }}"></td>
<td>{{ arm.alias }}</td>
.....
...
{% endfor %}
这是我的文件结构
解决方案
MEDIA_URL
您面临的问题是您已将/media/
. 因此,如果您更改MEDIA_ROOT
为/media
并将所有文件上传到,media/store/images
那么它应该可以工作。
像这样:
设置.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
模型.py
class Vechile(models.Model):
....
photo = models.ImageField(upload_to='store/images')
....
我希望这能解决你的问题。
推荐阅读
- python - 为什么 2captcha 不能解析 recaptcha?
- python - Django if elif else 语句
- java - 无法将当前目录从一个 spring 项目切换到另一个
- python - 弹性豆茎 cron 似乎不起作用
- javascript - 管道 got.stream 到文件
- elasticsearch - elasticsearch 架构/开发查询 - ADFS/安全过滤/SearchUI
- c# - 如何为 blazor 应用程序查找 svg 文本大小(以像素为单位)?
- java - 为没有参数的布尔方法编写 Junit 测试
- python - 使用 scikit-learn 的 RANSACRegressor 的 RANSAC 算法
- django - Django - 一次更新多个对象