Django:如何在管理面板中检测对象请求?

时间:2018-08-30 10:57:26

标签: python django django-models django-forms django-admin

更详细地说,我在管理面板中找到了名为Images的对象列表

class Image(models.Model):
    image = models.ImageField(upload_to='products/%Y/%m/%d/', 
    verbose_name=_('Image'), default='default.png')
    album = models.ForeignKey('Album', related_name='images')
    category = TreeForeignKey(Category, null=True) 
    likes = GenericRelation('Like', related_name='image_likes', null=True)
    is_main = models.BooleanField(default=False)
    is_slider = models.BooleanField(default=False)
    seen = models.IntegerField(default=0)
    seen_by_admin = models.BooleanField(default=False)


class ImageAdmin(admin.ModelAdmin):
    list_display = ['album', 'get_owner', 'is_main', 'is_slider','total_likes', 'seen', 'image_tag', ]
    list_filter = ['album', 'album__owner', 'is_main', 'is_slider', 'album__created_at']
    search_fields = ['album__name']
    list_per_page = 15 

只要 admin 或任何其他 superuser 输入任何Images.objectseen_by_admin字段应更改为seen_by_admin = True

1 个答案:

答案 0 :(得分:1)

您可以覆盖save_model方法:

class ImageAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.seen_by_admin=True
        super().save_model(request, obj, form, change)

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