In my models I have Document
model with foreign key to the Library
model.
When I am in Django admin site I want to disable editing and deleting Library
instances when I am creating new Document
.
What I tried was to remove delete and edit permissions by subclassing django.contrib.admin.ModelAdmin
and removing change/delete permissions
@admin.register(Library)
class LibraryAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None):
return False
def has_change_permission(self, request, obj=None):
return False
This makes unwanted buttons disappear but also entirely blocks possibility of editing and removing Libraries
, which is not what I want. Is there a way to disable these actions only in model edit form?
You could mark the request in the document admin:
def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
request._editing_document = object_id is not None # add attribute
return super(DocumentAdmin, self).changeform_view(request, object_id=object_id, form_url=form_url, extra_context=extra_context)
Now you can access that flag in the related admin:
@admin.register(Library)
class LibraryAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None):
if getattr(request, '_editing_document', False): # query attribute
return False
return super(LibraryAdmin, self).has_delete_permission(request, obj=obj)