【问题标题】:Django Admin : How to update/change the image from the list_display itself without opening the change form for the entryDjango Admin:如何在不打开条目更改表单的情况下从 list_display 本身更新/更改图像
【发布时间】:2017-06-05 23:16:14
【问题描述】:

我的 models.py 看起来像

class User_Detail(models.Model):
    user_image = models.ImageField(upload_to='users',default = 'users/profile.png')
    user_image_thumbnail = ImageSpecField(source='user_image',
                                      processors=[ResizeToFill(75, 100)],
                                      format='JPEG',
                                      options={'quality': 60})

我的 Admin.py 看起来像

class UserAdmin(admin.ModelAdmin):
    list_display = ('profile_pic',)

    def profile_pic(self, obj):  # receives the instance as an argument
        url = reverse('admin:%s_%s_change' %(obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )
        url_string = '<a style="margin: 2px;" href="%s">Update</a>' %(url)
        return '<img width=75 height=75 src="{thumb}" />'.format(
            thumb=obj.user_image_thumbnail.url,
        ) + url_string
    profile_pic.allow_tags = True
    profile_pic.short_description = 'User Picture'

我希望 django 管理员通过在显示的缩略图旁边提供一个更新按钮来更新管理列表显示本身的图像字段,并在不打开条目的更改表单的情况下保存它。 我正在使用 django-imagekit 生成缩略图。

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

    list_editable 用于编辑 django 管理列表中的字段,而无需转到更改表单。 不过使用list_editable要注意以下几点:

    • list_editable 中的字段也应包含在list_display
    • 不能将同一字段用作link 更改表单和list_editable

    你的 admin.py 应该是:

    class UserAdmin(admin.ModelAdmin):
        // "id" can be replaced by any other field to use as link
        list_display = ('id', 'profile_pic',)
        list_editable = ('profile_pic',)
    
        // rest of the code
    

    更多信息https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable

    【讨论】:

    • profile_pic 是 list_display 的自定义视图,而 list_editable 似乎不适用于 imagefield
    猜你喜欢
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2011-02-17
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多