Ozzy
Ozzy

Reputation: 177

Django Admin prevent delete on last record

I'm new to django and learning as I go.

I have a model that must have 1 record, therefore I want to prevent delete for the last record.

model.py

class SliderContent (models.Model):
    name = models.CharField(max_length=40)
    image = models.ImageField(upload_to='image')

I tried the following in admin.py

class SliderContentAdmin(admin.ModelAdmin):
.....
    def delete_model(self, request, obj):
     if last_record:
          storage = messages.get_messages(request)
          storage.used = True
          messages.error(request, 'Cannot delete last record.')
     else:
          obj.delete()

This didn't work, I have also looked at a pre_delete receiver but from what I have read this won't work as I'm using the build in Admin views.

What is the best way to do this?

Upvotes: 1

Views: 1950

Answers (1)

Alex Morozov
Alex Morozov

Reputation: 5993

Override the has_delete_permission() method:

from django.contrib.admin import helpers

class SliderContentAdmin(admin.ModelAdmin):
    min_objects = 1

    def has_delete_permission(self, request, obj):
        queryset = self.model.objects.all()

        # If we're running the bulk delete action, estimate the number
        # of objects after we delete the selected items
        selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
        if selected:
            queryset = queryset.exclude(pk__in=selected)

        if queryset.count() <= self.min_objects:
            message = 'There should be at least {} object(s) left.'
            self.message_user(request, message.format(self.min_objects))
            return False

        return super(SliderContentAdmin, self).has_delete_permission(request, obj)

Upvotes: 5

Related Questions