只允许从管理中删除模型的某些给定实例
在模型的管理中,我想仅允许对某些实例执行删除操作(我的模型有一个 DateTimeField,我想禁用将此字段设置为当前月份的实例的删除操作)。
有人可以帮忙吗?
谢谢
编辑
我尝试了克里斯在下面的回答中提出的方法,但 obj 始终为 None:
class UserProfileAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None):
# obj is always None
return super(UserProfileAdmin, self).has_delete_permission(request, obj=obj)
in the admin of a model I would like to allow the delete action only for some of the instances (my model has a DateTimeField and I would like to disable the delete action for instances which have this field set to the current month).
Anybody could help?
Thanks
EDIT
I tried the method proposed by Chris in his anser below, but obj is always None:
class UserProfileAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None):
# obj is always None
return super(UserProfileAdmin, self).has_delete_permission(request, obj=obj)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新:
它不是“始终无”,而是在可以确定特定对象时设置为特定对象。在更改列表中,特别是在尝试从更改列表中批量删除时的场景中,它被设置为
None
因为显然无法确定单个对象。如果您需要考虑从更改列表中删除,则必须创建自己的删除操作并替换默认的 Django 版本。类似于:
您实际上需要操作和原始
has_delete_permission
因为对象可以在其change_form 视图上单独删除。UPDATE:
It's not "always None", it's set to a specific object when a specific object can be ascertained. In the changelist, and particularly in your scenario when trying to bulk-delete from the changelist, it's set to
None
because no individual object can obviously be determined.If you need to account for deletion from the changelist, you'll have to create your own delete action and replace the default Django version. Something like:
You actually will need both the action and the original
has_delete_permission
since objects can be deleted individually on their change_form view.查看有关覆盖内置模型方法的文档: https://docs.djangoproject.com/en/1.3/topics/db/models/#overriding-model-methods
Check out the docs around overriding built-in model methods: https://docs.djangoproject.com/en/1.3/topics/db/models/#overriding-model-methods