【问题标题】:Django not show image on the viewDjango不在视图上显示图像
【发布时间】:2021-03-04 11:30:44
【问题描述】:

这是我的看法:

当我检查元素时,它给出的图像源是:

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)

views.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

settings.py

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_ROOT = os.path.join(BASE_DIR, 'store/images')
MEDIA_URL = '/media/'

models.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 %}

这是我的文件结构

【问题讨论】:

    标签: python html django image


    【解决方案1】:

    您面临的问题是您已将MEDIA_URL 设置为/media/。因此,如果您将MEDIA_ROOT 更改为/media 并将所有文件上传到media/store/images,那么它应该可以工作。

    像这样:

    settings.py

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
    MEDIA_URL = '/media/'
    

    models.py

    class Vechile(models.Model):
        ....
        photo = models.ImageField(upload_to='store/images')
        ....
    

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

    【讨论】:

    • 你能分享你models.py吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多