Tuesday, May 28, 2019

[Solved] How to disable the the Delete button

(I hate my email formatting)
- - - - - - - - - - - - - - - - - - - - - -
I asked too soon. Sorry.

There is a method in contrib.admin.options.BaseModelAdmin called ...
      
def has_delete_permission(self, request, obj=None):      """      Returns True if the given request has permission to change the given      Django model instance, the default implementation doesn't examine the      `obj` parameter.        Can be overridden by the user in subclasses. In such case it should      return True if the given request has permission to delete the `obj`      model instance. If `obj` is None, this should return True if the given      request has permission to delete *any* object of the given type.      """      opts = self.opts      codename = get_permission_codename('delete', opts)      return request.user.has_perm("%s.%s" % (opts.app_label, codename))  
 
So I made a callable ...

def see_delete(self, request, obj=None):      from django.contrib.auth import get_permission_codename      opts = self.opts      codename = get_permission_codename('delete', opts)      see = request.user.has_perm("%s.%s" % (opts.app_label, codename))      if obj:          if obj.company == get_user_company(request.user):              return see and True          else:              return False      return see    
In myModelAdmin I put ...  has_delete_permission = see_delete_button

And it works nicely :)  Open source is lovely and Django (and the Admin) is brilliant.

I'm guessing showing the button disabled would be a CSS task which I don't have the brain-space for just now.

Cheers

Mike

On 29/05/2019 8:37 am, Mike Dewhirst wrote:
Django 1.11 and Python 3.6 but upgrading to Django 2.2 (slowly)

Currently I use a get_readonly_fields callable in the Admin as documented[1]. The callable determines whether request.user is allowed to edit the editable fields or not. This works well.

However, the readonly user can still see/use the Delete button.

The abovementioned callable doesn't make their own records readonly so those users do need change (edit) permissions. Therefore I cannot use permissions to solve the problem.

Can anyone suggest an approach?

Thanks

Mike

[1] https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_readonly_fields




No comments:

Post a Comment