【问题标题】:Visualizing uploaded images in Django Admin在 Django Admin 中可视化上传的图像
【发布时间】:2016-07-10 16:44:31
【问题描述】:

虽然我找到了关于如何在 Django-Admin 中正确显示图像的有用帖子 (#1,#2,#3),但到目前为止我还没有成功地遵循这些建议。如下图所示,上传的图片没有正确显示,并显示 404 错误。

下图说明了上传的图片虽然已经成功上传到服务器,但没有显示出来:

当我用鼠标单击断开的链接时,浏览器上会显示以下错误:

编辑给定对象时,我还想知道如何显示缩略图 而不是图像的路径: 下面是我目前使用的配置:

settings.py

import os
PROJECT_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..').replace('\\','/')
SITE_ROOT = PROJECT_ROOT

# Path to media files, e.g. images
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'

urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from . import views

urlpatterns = patterns('',
    # some url configs here ... removed for simplification purposes ;-)
)

if settings.DEBUG is True:
    urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}) )
    #urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

class Image(models.Model):
    title = models.CharField(db_column='title', max_length=180, blank=True, null=True, help_text="Title of the image") 
    imagefile = models.ImageField(db_column='imagefile', upload_to='images', null=True, blank=True, help_text="Load an image.")
    #... some other fields here, removed for simplification purposes ;-)

    def image_(self):
        return '<a href="/media/{0}"><img src="/media/{0}"></a>'.format(self.imagefile)
    image_.allow_tags = True

    class Meta:
        managed = False
        db_table = 'image'
    
    def __unicode__(self):
        return u'%s' % (self.title)

admin.py

from django.contrib import admin
from .models import Image

class ImageAdmin(admin.ModelAdmin):
    list_display = ('title', 'description', 'image_', )
    search_fields = ('title', 'description')
    list_per_page = 25

admin.site.register(Image, ImageAdmin)

【问题讨论】:

    标签: python django django-models django-admin media-url


    【解决方案1】:

    这个答案至少延迟了一年,但是,如果你仍然有同样的问题,你可以这样解决:

    首先,假设您的 django 项目具有此架构并且您正在运行 django 2.0

    . django_test
    |_ django_test
    |  |_ __init__.py
    |  |_ settings.py
    |  |_ urls.py
    |  |_ wsgi.py
    |_ media
    |  |_ author_headshot
    |_ my_app
    |  |_ admin.py
    |  |_ __init__.py
    |  |_ apps.py
    |  |_ migrations
    |  |_ models.py
    |  |_ tests.py
    |  |_ urls.py
    |  |_ views.py
    |_ static
    |_ templates
    

    然后,添加您的 django_test/settings.py

    # static files will be stored in 'static' folder
    STATIC_URL = '/static/'
    STATICFILES_DIR = [
        BASE_DIR + '/static'
    ]
    # media files will be stored in 'media' folder
    MEDIA_URL = '/media/'
    MEDIA_ROOT = BASE_DIR + '/media'
    

    然后,在 django_test/urls.py 中确保添加 MEDIA_URLMEDIA_ROOT 的静态路径,如下例所示: p>

    from django.contrib import admin
    from django.conf import settings
    from django.conf.urls.static import static
    from django.urls import path
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        # More paths/urls
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    最后,在您的应用程序模型中,您可以为每个 ImageField 添加一个唯一文件夹,用于存储媒体文件,如下例所示:

    my_app/models.py

    from django.db import models
    from django.utils.html import format_html
    
    class Author(models.Model):
        # My models ...
        # Here, the media files will be stored in my_project/media/author_headshot
        headshot = models.ImageField(upload_to='author_headshot')
    
        # If you want to show the media files in the list display in the admin panel:
        def image_tag(self):
            return format_html('<img href="{0}" src="{0}" width="150" height="150" />'.format(self.headshot.url))
    
        image_tag.allow_tags = True
        image_tag.short_description = 'Image'
    

    然后,在 my_app/admin.py 中:

    from django.contrib import admin
    from . import models
    
    @admin.register(models.Author)
    class AuthorAdmin(admin.ModelAdmin):
        list_display = ('image_tag',)
    

    最后,你的媒体文件会有这样的 url:

    http://example.domain/media/file_path.extension

    django 管理面板截图:

    【讨论】:

    • 这能解决编辑模式下的图像预览问题吗?
    【解决方案2】:

    你有没有尝试过这样的事情:

    admin.py

    from django.contrib import admin
    from .models import Image
    
    class ImageAdmin(admin.ModelAdmin):
        list_display = ('title', 'description', 'image_display', )
        search_fields = ('title', 'description')
        list_per_page = 25
    
        def image_display(self, obj):
            return '<a href="/media/{0}"><img src="/media/{0}"></a>'.format(self.imagefile.url)
        image_.allow_tags = True
        image.short_descripition = u'IMAGE'
    
    admin.site.register(Image, ImageAdmin)
    

    这总是对我有用。让我知道这是否有帮助。

    【讨论】:

      【解决方案3】:

      使用ImageField 和使用image_(self) 函数使图像可见时会有细线。见下图: this is the link of the image 因为我的名誉不允许我发布图片。 img1 列代表您在 models.py中使用的 imagefile 变量>


      ImageField的图片保存在your-project/media/images目录下的images文件夹中。


      当您使用“media/{0}”时,您的 image_(self) 函数会指向更深一层,即它会指向 your- project/media//media/images (注意这里的 // 由于 /{0} 的额外 / 而出现)。你的函数应该修改如下:


      def image_tag(self):
          return '<a href="{0}"><img src="{0}" width = "120" height = "120"></a>'.format(self.img1.url)
      image_tag.allow_tags = True
      image_tag.short_description = 'y-Image'
      

      【讨论】:

        猜你喜欢
        • 2018-12-11
        • 2010-10-29
        • 2014-04-29
        • 2012-05-28
        • 1970-01-01
        • 2013-10-22
        • 2021-07-27
        • 1970-01-01
        • 2017-01-07
        相关资源
        最近更新 更多