Django Tips & Tricks #6 - Make Deleting Easy In Admin

8 min read
Lets say we have a model as shown in some project.
from django.db import models

class Resource(models.Model):
"""
Model to hold resources for books.
"""
book = models.ForeignKey('Book')
book_type = models.IntegerField()
url = models.URLField()
This model can be registered in admin as follows.
from django.contrib import admin

from . import models

class ResourceAdmin(admin.ModelAdmin):
list_display = ('book', 'book_type', 'url')


admin.site.register(models.Resource, ResourceAdmin)
This will generate a nice admin interface to modify the data.
django-admin-delete
Now if we want to delete a record, we need to follow these steps.
  • First, we have to select that record
  • Next, we have to click on the action dropdown
  • Next, we have to select delete action
  • Next, we have to click Go button.
  • In the next page we have to confirm that we have to delete.
Just to delete a single record, we have to click 5 times. That's too many clicks for a single action.
To simplify the process, we can have simple delete button for the objects as shown. This can be achieved by writing a function which will insert delete button for every record.
from django.contrib import admin

from . import models


class ResourceAdmin(admin.ModelAdmin):
def delete(self, obj):
return '<input type="button" value="Delete" onclick="location.href=\'%s/delete/\'" />'.format(obj.pk)

delete.allow_tags = True
delete.short_description = 'Delete object'

list_display = ('book', 'book_type', 'url', 'delete')


admin.site.register(models.Book)
Now we have an admin with delete button for the records.
django-admin-delete
To delete an object, just click on delete button and then confirm to delete it. Now, we are deleting objects with just 2 clicks.

Read more django tips.
Read more posts about django.

Tags: django | django-tips-tricks | python

I am Chillar Anand. I daydream a lot and write about the things that interest me here. You can read more about this blog here.

See all articles

RSS Feed for the blog

Edit this page

Comments

Comments powered by Disqus