作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有:
class Person(admin.ModelAdmin):
actions = ['delete_selected']
def delete_selected(modeladmin, request, queryset):
# Show confirmation page.
for obj in queryset:
obj.custom_delete()
最佳答案
简短回答 :您应该覆盖 delete_queryset
[Django-doc] ,因为这封装了删除对象的真实逻辑。
您不应覆盖 delete_selected
。这个 Action 是 defined like [GitHub] :
def delete_selected(modeladmin, request, queryset):
# ...
# Populate deletable_objects, a data structure of all related objects that
# will also be deleted.
deletable_objects, model_count, perms_needed, protected = modeladmin.get_deleted_objects(queryset, request)
# The user has already confirmed the deletion.
# Do the deletion and return None to display the change list view again.
if request.POST.get('post') and not protected:
if perms_needed:
raise PermissionDenied
n = queryset.count()
if n:
for obj in queryset:
obj_display = str(obj)
modeladmin.log_deletion(request, obj, obj_display)
modeladmin.delete_queryset(request, queryset)
modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
"count": n, "items": model_ngettext(modeladmin.opts, n)
}, messages.SUCCESS)
# Return None to display the change list page again.
return None
# ...
context = {
# ...
}
request.current_app = modeladmin.admin_site.name
# Display the confirmation page
return TemplateResponse(request, modeladmin.delete_selected_confirmation_template or [
"admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.model_name),
"admin/%s/delete_selected_confirmation.html" % app_label,
"admin/delete_selected_confirmation.html"
], context)
delete_selected.allowed_permissions = ('delete',)
delete_selected.short_description = gettext_lazy("Delete selected %(verbose_name_plural)s")
modeladmin.delete_queryset(request, queryset)
delete_queryset
就足够了:
class PersonAdmin(admin.ModelAdmin):
actions = ['delete_selected']
def delete_queryset(self, request, queryset):
for obj in queryset:
obj.custom_delete()
ModelAdmin
有一个
standard implementation for delete_queryset
[GitHub] :
class ModelAdmin(BaseModelAdmin):
# ...
def delete_queryset(self, request, queryset):
"""Given a queryset, delete it from the database."""
queryset.delete()
关于django - 有没有办法覆盖 ModelAdmin 中的 delete_selected 方法但保持确认?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56450998/
在 admin.py 文件中我粘贴: admin.site.disable_action('delete_selected') 并得到一个错误: KeyError at / 'delete_selec
我正在尝试覆盖名为 Invoice 的模型的 delete 方法。模型发票由模型 Action 中的 ForeignKey 引用。我想在删除发票时更新模型 Admin 中名为 billed 的 Boo
我有: class Person(admin.ModelAdmin): actions = ['delete_selected'] def delete_selected(modela
我正在使用 Django 3.2b1 和 pytest 6.2.2。 我正在尝试使用 pytest 编写测试以确保管理员能够使用 delete_selected 删除对象行动。我的测试是这样的: de
我是一名优秀的程序员,十分优秀!