Paul R
Paul R

Reputation: 2797

Django admin: prevent add, change, but not delete

I want to be able to only delete values from admin. I wrote following code for this:

def has_add_permission(self, request):
    return False

def has_change_permission(self, request, obj=None):
    return False

def has_delete_permission(self, request, obj=None):
    return True

However, in this case I can't find link to delete object. How this can be resolved?

Upvotes: 2

Views: 1817

Answers (1)

allcaps
allcaps

Reputation: 11228

It makes sense that the change list view is disabled. I noticed that visiting /admin/app/model/1/delete/ will let you delete the object.

So you have basically two options:

  1. Create a custom admin page listing the models objects. Each object with a delete button that links to /admin/app/model/pk/delete/. Hook this into your admin somehow.
  2. Set has_change_permission to True and make sure the detail page displays a custom form, all fields with readonly widgets.

I would go for 2. Because it is less work, gives you all the benefits of the change list page (filters, actions) and keeps the default admin structure. A large benefit is that the user can see what he is about to delete.

I would do something like this (not tested):

class ItemForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        for field in self.fields: 
            self.fields[field].widget.attrs['readonly'] = True

    class Meta:
        model = Item
        exclude = []

class ItemAdmin(admin.ModelAdmin):
    form = ItemForm

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return True

    def has_delete_permission(self, request, obj=None):
        return True

Upvotes: 3

Related Questions