Django Admin - 禁用特定模型的“添加"操作

2022-01-25 00:00:00 python django django-admin

问题描述

我有一个 django 网站,里面有很多模型和表格.我有许多自定义表单和表单集以及内联表单集以及自定义验证和自定义查询集.因此,添加模型操作取决于需要其他东西的表单,并且 django 管理员中的添加模型"通过自定义查询集中的 500.

I have a django site with lots of models and forms. I have many custom forms and formsets and inlineformsets and custom validation and custom querysets. Hence the add model action depends on forms that need other things, and the 'add model' in the django admin throughs a 500 from a custom queryset.

是否可以禁用某些型号的添加 $MODEL"功能?

Is there anyway to disable the 'Add $MODEL' functionality for a certain models?

我希望 /admin/appname/modelname/add/ 给出 404(或合适的离开"错误消息),我不希望出现添加 $MODELNAME"按钮在 /admin/appname/modelname 视图上.

I want /admin/appname/modelname/add/ to give a 404 (or suitable 'go away' error message), I don't want the 'Add $MODELNAME' button to be on /admin/appname/modelname view.

Django admin 提供了一种禁用管理操作的方法 (http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#disabling-actions) 但是此模型的唯一操作是 'delete_selected'.即管理员操作仅对现有模型起作用.有没有一些 django 风格的方法来做到这一点?

Django admin provides a way to disable admin actions (http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#disabling-actions) however the only action for this model is 'delete_selected'. i.e. the admin actions only act on existing models. Is there some django-esque way to do this?


解决方案

很简单,只需像这样在 Admin 类中重载 has_add_permission 方法:

It is easy, just overload has_add_permission method in your Admin class like so:

class MyAdmin(admin.ModelAdmin):
     def has_add_permission(self, request, obj=None):
        return False

相关文章