python-3.xdjangodjango-modelsdjango-admin

custom delete action admin class in django


I want to custom delete action admin class with overwrite function delete in admin.py , but it dosn't work ! this is the error : Post with ID “<django.db.models.query_utils.DeferredAttribute object at 0x0000020BF060A450>” doesn’t exist. Perhaps it was deleted?

I read and used this code at following site but it wasn't work:

the site I used it

class PostAdmin(admin.ModelAdmin):
    list_display = ('delete',)
    def delete(self, obj):
        view_name = "admin:{}_{}_delete".format(obj._meta.app_label, obj._meta.model_name)
        link = reverse(view_name, args=[Post.id])
        html = '<input type="button" onclick="location.href=\'{}\'" value="Delete" />'.format(link)
        return format_html(html)

Solution

  • Use obj.id, not Post.id:

    class PostAdmin(admin.ModelAdmin):
        list_display = ('delete',)
    
        def delete(self, obj):
            view_name = 'admin:{}_{}_delete'.format(
                obj._meta.app_label, obj._meta.model_name
            )
            link = reverse(view_name, args=[obj.id])
            return format_html(
                '<input type="button" onclick="location.href=\'{}\'" value="Delete" />',
                link,
            )