【问题标题】:Display images form the admin panel从管理面板显示图像
【发布时间】:2019-06-03 23:32:53
【问题描述】:

我想制作一个应用程序,其中管理员在管理面板上上传图像并显示在模板上。我知道有一些与此相关的问题,但我尝试了所有这些但仍然无法显示图像。 Django 版本:2.1.4 python版本:3.6.7

在setting.py中

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'image')

在model.py中

from django.db import models

class ImageModel(models.Model):
    caption = models.CharField(max_length=40)
    image = models.ImageField(upload_to='uploadImage', blank=True)

    def __str__(self):
        return self.caption 

在 view.py 中

from django.shortcuts import render
from .models import ImageModel

def image_page(request):
    images = ImageModel.objects.all()
    return render(request, 'input/hello.html', {'image':images})

在 urls.py 中

from django.contrib import admin
from django.urls import path, include
from image import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.image_page),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在 imageShow.html 中

<img src="{{ ImageModel.image.url }}" alt="image" /> 

这样做会显示一个损坏的图像,有时还会显示图像的完整 URL(图像保存在哪里)我做错了什么。我尝试在views.py中打印可变图像并打印我的标题(“图像”),所以这意味着它在img标签中发送标题而不是图像本身?我应该创建一个新的 ImageUpload 类吗? 提前致谢

【问题讨论】:

  • 你安装Pillow了吗?
  • 是枕头==5.3.0
  • 那么下面的答案应该可以纠正您的问题
  • 不,答案是返回图像的路径 /media/uploadImage/back.jpg

标签: python django


【解决方案1】:

您需要遍历ImageModel queryset(您通过变量image 作为上下文发送)并在模板中显示图像,如下所示:

{% for im in image %}
    <img src="{{ im.image.url }}" alt="image" />
{% endfor %}

【讨论】:

  • 我已经尝试过了,它曾经将图像的路径发回给我。
  • 先生,我已经尝试在 image.objects.all() 中获取图像:并打印图像它返回 ]>
  • 那是因为它是一个查询集。顺便说一句,你如何为你的形象服务?你在用这个:docs.djangoproject.com/en/2.1/howto/static-files/… 吗?
  • I try to print variable images in views.py and it print my caption("image") so it means that it sending caption in img tag not the image itself?。不确定您在问什么,但通过{ 'image': images } 您正在将查询集发送到模板。它是ImageModel 对象的集合(不是实际图像)。因此,在模板中,您需要遍历该对象集合并获取图像 url(同样,不是实际图像)。使用该图像 url,您可以在 img 标记中显示图像。对于某些ImageModel 对象,您可能没有任何图像,这可能是导致图像损坏的原因。
  • 如果我没有任何图像,则不应将 image.id 返回到此 /media/uploadImage/back.jpg 。现在我正在尝试这个stackoverflow.com/questions/16307307/…
猜你喜欢
  • 2015-10-25
  • 1970-01-01
  • 2011-04-19
  • 2020-09-27
  • 2011-10-11
  • 2011-01-27
  • 1970-01-01
  • 2017-12-17
  • 2015-01-27
相关资源
最近更新 更多