首页 > 解决方案 > 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 %}

这是我的文件结构

在此处输入图像描述

标签: pythonhtmldjangoimage

解决方案


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')
    ....

我希望这能解决你的问题。


推荐阅读