简体   繁体   English

在 Django Admin 中可视化上传的图像

[英]Visualizing uploaded images in Django Admin

Although I've found useful posts on how to correctly display images in the Django-Admin ( #1 , #2 , #3 ), I've so far not succeeded to follow the advices.虽然我找到了关于如何在 Django-Admin 中正确显示图像的有用帖子( #1#2#3 ),但到目前为止我还没有成功地遵循这些建议。 As you can see below, the uploaded images are not being properly visualized and an 404 error is being displayed.正如您在下面看到的,上传的图像没有正确显示,并且显示 404 错误。

The Figure below illustrates the fact that the uploaded images are not being displayed although they've been successfully uploaded on the server:下图说明了虽然上传的图片已经成功上传到服务器,但没有显示的事实: 上传图片的链接失效

When I click with the mouse on the broken link, the following error is displayed on the browser:当我用鼠标单击断开的链接时,浏览器上会显示以下错误: 网址错误

When editing a given object, I was also wondering how to display a thumbnail and not the path of the image:编辑给定对象时,我还想知道如何显示缩略图而不是图像的路径: 图片的网址 Below, you can find the configuration that I've been using so far:下面,您可以找到我迄今为止一直在使用的配置:

settings.py设置.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网址.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模型.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管理员.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)

have you tried something like this:你有没有尝试过这样的事情:

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)

That always work for me.那总是对我有用。 Let me know if that helped.如果这有帮助,请告诉我。

This answer is delayed by at least one year, but, still, if you still have the same problem, you can fix it like this way:这个答案至少延迟了一年,但是,如果你仍然有同样的问题,你可以像这样修复它:

First of all, let's suppose your django project have this architecture and you're running django 2.0 :首先,让我们假设您的 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

Then, add in your django_test/settings.py :然后,添加您的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'

Then, in django_test/urls.py make sure to add the static path of your MEDIA_URL and MEDIA_ROOT like this example:然后,在django_test/urls.py 中确保添加MEDIA_URLMEDIA_ROOT的静态路径,如下例所示:

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)

And finally, in your application model, you can add a unique folder for each ImageField where your media files will be stored like this example:最后,在您的应用程序模型中,您可以为每个 ImageField 添加一个唯一的文件夹,您的媒体文件将在其中存储,如下例所示:

In my_app/models.py :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'

Then, in my_app/admin.py :然后,在my_app/admin.py 中

from django.contrib import admin
from . import models

@admin.register(models.Author)
class AuthorAdmin(admin.ModelAdmin):
    list_display = ('image_tag')

Finally, your media files will have this kind of urls:最后,您的媒体文件将具有以下网址:

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

Screenshots of the django admin panel: django 管理面板的屏幕截图:

在此处输入图片说明

在此处输入图片说明

there is fine line when you use the ImageField and when you use the function image_(self) to make the image visible.有细线条当您使用的ImageField,当你使用函数image_(个体经营),以使图像可见。 See the diagram below: this is the link of the image as my reputation does not allow me to post image.见下图:这是图片的链接,因为我的声誉不允许我发布图片。 The img1 column represents the imagefile variable you used in models.py . img1列代表您在models.py 中使用的imagefile变量。


The images of ImageField are saved in images folder which is the directory your-project/media/images . ImageField的图像保存在图像文件夹中,该文件夹是your-project/media/images 目录


Your image_(self) function is pointing to one level deeper when you are using " media/{0} " ie it will point to your-project/media//media/images (notice the // here which is coming due to extra / of /{0}) .当您使用“ media/{0} ”时,您的image_(self)函数指向更深的一层,即它将指向your-project/media//media/images (注意这里的 // 由于额外/ / {0}) Your functions should be modified as follows:您的函数应修改如下:


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'

如果您是 Chrome 用户,请尝试“Chrome 的 Web 服务器”扩展程序,您可以在此处找到: https<\/a> :\/\/stackoverflow.com\/a\/46480984\/14508690

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM