How to customize the admin actions in list pages of Django admin?

Django by default provides automatic admin interface, that reads metadata from your models to provide a beautiful model interface where trusted users can manage content on your site. The admin is enabled in the default project template used by startproject so we don't need to worry of the settings.

By default the model won't get displayed in the admin panel, to make the models of our application visible in the admin panel we have to regsiter the models in admin.py with admin.

In models.py

STATUS_CHOICES = (
    ('d', 'Draft'),
    ('p', 'Published'),
    ('r', 'Review'),
    ('t', 'Trash'),
)

class BlogPost(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    status = models.CharField(max_length=1, choices=STATUS_CHOICES)
    created_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

In admin.py

admin.site.register(BlogPost)

Customizing the admin actions:

When we register our app with the admin we’ll see the table in the admin panel. By default it will come with ‘delete selected’ action in the list page.
Now we want to add some actions like Publish the selected posts or Draft the selected posts. then we would be override the ModelAdmin and write our custom action in admin.py
In admin.py

class BlogPostAdmin(admin.ModelAdmin):

    actions = ['publish_selected']

    def publish_selected(self, request, queryset):
        queryset.update(status='p')

    publish_selected.short_description = "Publish the selected posts"

In the above snippet actions atribute of  BlogPostAdmin adds the new action ‘‘publish_selected'’ to the actions dropdown. And the coresponding business logic will be written in the mothod ‘‘publish_selected'’. The short_description that is given will be displayed in the dropdown, in the current case it is Publish the selected posts.
In the above scenario the action will be added only to the BlogPost table only in the admin panel, to make the above action to be added for all other tables in the admin panel we need to write the method globally and add that to add_action.

In admin.py

def publish_selected(modeladmin, request, queryset):
    queryset.update(status='p')

publish_selected.short_description = "Publish the selected posts"

admin.site.add_action(publish_selected')

You can disable any action globally by using disable_action method of django admin.

admin.site.disable_action('delete_selected')

The above line would disable 'delete_selected' for all the models. If you want to enable the action for single model and disable for all other models then in admin.py

admin.site.disable_action('delete_selected')

class BlogPostAdmin(admin.ModelAdmin):

    actions = ['delete_selected', 'publish_selected']

    def publish_selected(self, request, queryset):
        queryset.update(status='p')

    publish_selected.short_description = "Publish the selected posts"


The above line will add ‘delete_selected’ only for ‘BlogPostAdmin’ model.

If you want to remove ‘delete_selected’ for only Single model then we have to override the get_actions method of Django model admin and delete the corresponding ‘action’.

In admin.py

class BlogPostAdmin(admin.ModelAdmin):

    actions = ['delete_selected', 'publish_selected']

    def publish_selected(self, request, queryset):
        queryset.update(status='p')

    publish_selected.short_description = "Publish the selected posts"

    def get_actions(self, request):
        # Disable delete
        actions = super(BlogPostAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

The above will disable the ‘delete_selected’ only for BlogPostAdmin model.

Posted On 30 April 2014 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
How to maintain user session across sub domains in Django

Nowadays, people are using wildcard domains to provide same user experience across different domains. Using subdomains, we can be able to host multiple sites with …

Continue Reading...
What is Django CRM and it’s advantages

Here in this blog you can find about CRM, Importance of CRM in sales, Types of CRM, How django crm helps for business and it’s …

Continue Reading...
Implementation of single sign on using auth0 in django application

As the no of applications increases, users need to create username & passwords, need to remember for each application. Users can't remember these details and, …

Continue Reading...
Customizing Django REST API Serializers

Customizing Django REST API Serializers

Continue Reading...
How to implement TokenBasedAuthentication in DjangoRestFramework?

This blog explains you how to use Token Authentication to authenticate users within a Django Application. Token Authentication is a way to authorize users by …

Continue Reading...
Understanding middleware functionality in django2.0

Understanding new style of middleware in Django2.0, the difference between old-style & new-style. How to write custom middlewares in new-style and upgrading from old-style middleware.

Continue Reading...
Django acceptance testing automation with robot framework

Acceptance testing automation for django web and REST applications using a robot testing framework.

Continue Reading...
How to filter a Django Queryset using Extra

Using SQL Queries in Django ORM - Filtering extra objects within in a single query, to reduce the number of queries.

Continue Reading...
Overriding Django Model behaviour with Proxy Model

The main Usage of a proxy model is to override the main functionality of existing Model. It is a type of model inheritance without creating …

Continue Reading...
how to pass extra context data to serializers in django-rest-framework ?

Django rest-framework passes extra context data to serializers for the best design of rest applications. we can use "context" parameter in serializers to pass extra …

Continue Reading...
Understanding Routers in Django-Rest-Framework

By using routers in django-rest-framework we can avoid writing of url patterns for different views. Routers will save a lot of time for developing the …

Continue Reading...
Django Single Sign On(SSO) to multiple applications

Single sign on is a way for users to issue a security token for the first time login, login into multiple applications using one set …

Continue Reading...
How to Document API Requests using Django Rest Swagger

Django Rest Swagger is used to Document your API for eg., Listing all Your project Rest API's in the browser with brief description about the …

Continue Reading...
Django webpacker - A compression tool to bundles css, js files

django-webpacker is a django compressor tool which bundles css, js files to a single css, js file with webpack and updates your html files with …

Continue Reading...
What's great about Django girls to inspire women into programming

Django girls is a non-profit organization, that helps women to learn Django programming language and to inspire them into programming. They are organizing workshops all …

Continue Reading...
How to use nested formsets in django

Django Formsets manage the complexity of multiple copies of a form in a view. By using formsets, you can know how many forms were their …

Continue Reading...
How to convert xml content into json using xmltodict

We need to process large amounts of data to get the desired results from XML file. xmltodict will help you to process, give JSON formatted …

Continue Reading...
Custom validations for serializer fields Django Rest Framework

we can write custom validations for serializer fields in Django Rest Framework. Validators are used to validate the data whether it is semantically valid or …

Continue Reading...
How To Add A Custom Managers In Django

Django Custom Managers - A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for …

Continue Reading...
Introduction to API development using Django REST framework with Example

Introduction to API development with Django REST framework. You can build the API for any Django application. Pre-requisites are Django and OOPS(object oriented programming concepts) …

Continue Reading...
Django-REST Framework Object Level Permissions and User Level Permissions

Django-REST User Level Permissions and Object Level Permissions. User Level Permissions and Object level Permissions allow to serve customers based on their access levels or …

Continue Reading...
Using Python weasyprint generate HTML to PDF in django

WeasyPrint is to combine multiple pieces of information into an HTML template and then converting it to a PDF document.

Continue Reading...
How to create thumbnail image in Django templates using sorl-thumbnail?

Sorl thumbnail is the package which is being widely used to generate thumbnail in Django. It will create thumbnail of given size for the given …

Continue Reading...
Deploying Your Django app on Heroku

Heroku is a platform as a service (PaaS) that enables developers to build and run applications entirely in the cloud.
1. installation
2. Creating and Deploying app.
3. …

Continue Reading...
Django Template language Intro

We can write the required logics based on programming[python] syntax in models and views but, when we want to write simple logics we should follow …

Continue Reading...
Using Gitlab API, integrating gitlab in django project for authentication and access

This is a simple way to integrate gitlab authentication in your django apps.

We can get user verified email id, general information, git lab URL …

Continue Reading...
Django Conditional Expressions in Queries

Reduce database queries in django with Conditional Expressions. By using Conditional Expressions we can use "If...Elif...Else" expressions while querying the database so that we can …

Continue Reading...
Sorl-thumbnail to generate thumbnails in django

Displaying and Customizing the images in django with sorl-thumbnail.

Continue Reading...
How to Create initial django migrations for existing DB schema.

Django provides the comfort database migrations from its version 1.8, with which we can avoid the usage of third party packages like south. Adding migrations …

Continue Reading...
Django - Database access optimization

Django - Database access optimization, Django Queryset is generally lazy in nature. It will not hit the database until it evaluates the query results.

Continue Reading...
Querying with Django Q objects

Querying with Django Q objects: Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects …

Continue Reading...
Integration Of GitHub API with python django

Using Github integration, we can get the user verified email id, general information, git hub URL, id, disk usage, public, private repo's, gists and followers, …

Continue Reading...
Django - migrating from function based views to class based views

The single most significant advantage in Django class-based views is inheritance. On a large project it's likely that we will have lots of similar views. …

Continue Reading...
How To Write Custom migrations in Django

This blog post will help you to get deeper into Django Migrations - how Migrations works and how to create or add our custom migrations. …

Continue Reading...
Dynamically Adding Google Maps with Marker In Django

Google Maps allows you to display maps on your web site, we can also customize maps, and the information on maps.
The Google Maps API is …

Continue Reading...
Django Unit Test cases with Forms and Views

By writing unit test cases, you can evaluate each code component in the initial stage itself and it'll improve your app/code performance. Which is the …

Continue Reading...
Understanding Checkout flow in Django Oscar.

Explaining Django Oscar checkout flow.

Continue Reading...
How to monitor django application live events with sentry

Let us now learn how to track exceptions and events in SENTRY. We will setup browser and server end tracking for Django Project.

Continue Reading...
Integration Of Linkedin API in python django

Using Linkedin integration, we can get the user verified email id, general information, work history in a less span of time, and a user can …

Continue Reading...
Django efficient implementation of Amazon s3 and Cloudfront CDN for faster loading.

Django by default to store the files in your local file system. To make your files load quickly and secure we need to go for …

Continue Reading...
How to create Custom User Model or Extend User Model in Django?

Django provides built in authentication which is good for most of the cases, but you may have needs that are being served with the existing …

Continue Reading...
Working with Django Plugins

This blog describes about how to work with django-plugins. Django Plugin is a Simple Plugin Framework for Django. By using django-plugins, you can make your …

Continue Reading...
Export html web page to pdf using jspdf

jsPDF is used to generate pdf files in client-side Javascript. You can find the links for jsPDF here and also you can find the link …

Continue Reading...
Preserve file names with sorl for better SEO

We use sorl-thumbnail for scaling images by keeping the original one intact. Sorl proven to be great tool for generating different sized images throughout website. …

Continue Reading...
Custom Password Less Authentication in Django

Authentication backends allow the ability to change what method checks your users credentials.

For web services, ie Facebook authentication, you don't have access to user …

Continue Reading...
Improving page speed score in Google Page Score test- PART2

In our previous blog post we got an idea of what are the things that Google's Page Speed Insights will take into count to give …

Continue Reading...
Extract text with OCR for all image types in python using pytesseract

Optical Character Recognition(OCR) is the process of electronically extracting text from images or any documents like PDF and reusing it in a variety of ways …

Continue Reading...
Factory Boy - An alternative for Fixtures

Factory Boy is a fixtures replacement tool. It allows you to use objects customized for the current test, while only declaring the test-specific fields. For …

Continue Reading...
Improving page speed score in Google Page Score test- PART1

Google's Page Speed Insights measures the performance of a page for mobile devices and desktop devices. It fetches the url twice, once with a mobile …

Continue Reading...
Integration of 2checkout with django

Payment Gateways which facilitate communication within banks and Security is an integral component of all payment gateways, as sensitive data such as Credit Card Numbers …

Continue Reading...
Get count, average, min, max values from model field using Django Aggregate

To retrieve maximum, minimum or average values from group of rows we can use django Aggregation. For example to retrieve max price or avg price …

Continue Reading...
Set Up Travis CI For Django project

Travis CI is a continuous integration service used to build and test applications hosted at GitHub. Here are simple steps to add CI to you …

Continue Reading...
Sending emails using sendgrid on heroku for a Django App

Integrate Sendgrid API to your Heroku app to deliver simplified emails like any notification emails, user signups etc.

Continue Reading...
Django Custom Template Tags And Filters

Django Template Tags are simple Python functions that accept a value, an optional argument, and return a value to be displayed on the page.
First, In …

Continue Reading...
Python Memcached Implementation for Django project

Memcache is a memory caching system that helps web applications and mobile app backends to improve performance and scalability. We should consider using Memcache when …

Continue Reading...
How to customize Django Oscar Models, Views and URL's

In order to customize models, views and urls, you need to fork an Oscar core app in which model/view resides. Then you should be able …

Continue Reading...
Integrate Django-Oscar-Accounts with Django-Oscar

This package uses double-entry bookkeeping where every transaction is recorded twice (once for the source and once for the destination). This ensures the books always …

Continue Reading...
Google plus API integration with django

Using GPlus integration, we can get the user verified email id, general information, friends in a less span of time, and user can also share …

Continue Reading...
Extract data from PDF and all Microsoft Office files in python

The quick way to get/extract text from PDFs in Python is with the Python library "slate". Slate is a Python package that simplifies the process …

Continue Reading...
django Payu Payment gateway Integration

In this blog, we will see how to integrate Django and PayU Payment Gateway. To integrate with PayU, we have package called "django-payu" - a …

Continue Reading...
Running Django with PyPy to boost performance

Running Django with PyPy to boost performance

Continue Reading...
How to Create your own e-commerce shop using Django-Oscar.

Oscar is an open-source ecommerce framework for Django. Django Oscar provides a base platform to build an online shop. Oscar is built as a highly …

Continue Reading...
Setting Up Coveralls for Django Project

Coveraslls will check the code coverage for your test cases. To use coveralls.io your code must be hosted on GitHub or BitBucket.

install coveralls
pip …

Continue Reading...
Sendgrid Inbound Email Parsing with django

Using the Inbound parse webhook, we can parse the contents, attachments of an incoming email.

Inbound Parse API follows 3 steps:
1. sending an email …

Continue Reading...
How to customize the admin actions in list pages of Django admin?

Django by default provides automatic admin interface, that reads metadata from your models to provide a beautiful model interface where trusted users can manage content …

Continue Reading...
Handling Custom Error Pages(404, 500) In Django

404 Page not found and 500 Internal server errors generally occur in every website. When these errors occurs, generally for Django application it will load …

Continue Reading...
Autocomplete with Django-Haystack and Elasticsearch with single letter querying.

Django's haystack provides autocomplete functionality. To do autocomplete effectively, the search backend(elasticsearch in this case) uses n-grams (essentially a small window passed over the string). …

Continue Reading...
How to create Periodic Tasks with Django Celery?

Celery provides asynchronous job queues, which allows you to run Python functions in the background. Celery is on the Python Package Index (PyPi), and can …

Continue Reading...
Best Practices of Using Django Celery in Django Social Auth

Best Practices of Using Django Celery in Django Social Auth.

Continue Reading...
Custom Decorators To Check User Roles And Permissions In Django

A decorator is a function that takes another function and returns a newer,prettier version of that function.

To know more about decorators in python see …

Continue Reading...
Implement search with Django-haystack and Elasticsearch Part-1

Haystack works as search plugin for django. You can use different back ends Elastic-search, Whose, Sorl, Xapian to search objects. All backends work with same …

Continue Reading...
How to index binary files in django haystack

Now we are going to index text content which is stored in structured files such as PDFs, Microsoft Office documents, images, etc using haystack and …

Continue Reading...
Understanding django serializers with examples

Serializers are used for “translating” Django models into other formats like xmi,json,yaml(YAML Ain’t a Markup Language)

from django.core import serializers
data = serializers.serialize("xml", SomeModel.objects.all())

Continue Reading...
Introduction to Django's Class based views - Understanding how a class based view works

Django has MVT architecture. A view in django is just a callable that takes a request and returns a response. But this can be more …

Continue Reading...
Understanding Django Permissions And Groups

Django comes with a simple permissions system. It provides a way to assign permissions to specific users and groups of users. We can have permissions …

Continue Reading...
Django Inclusion Tags

Django’s template system comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. You can …

Continue Reading...
Dynamic Models in Django (adding new fields to models from admin)

Some times in the production level there may be a chance of adding new fields to our model.With the normal django models when we add …

Continue Reading...
E-commerce (paypal) integration with Django

E-commerce is integration is becoming almost essential for every web application now a days. There are so many payment gateways to integrate with our application. …

Continue Reading...
Hosting Django Application with Nginx and UWSGI

Django is a python based web- application development framework. Setting up a sample app and running it as easy as pie. Nginx is a webserver …

Continue Reading...
Django Generic many to many field implementation

Django application has a GM2MField that combines the features of the standard Django "ManyToManyField" and "GenericForeignKey".

Installation:
pip install django-gm2m

Continue Reading...
Django Subdomains to do advanced things

We always struggle to give users customization's even before they login to the system like abc.micropyramid.com and django don't know how to handle that out …

Continue Reading...
Using Django's built in signals and writing custom signals.

Django has a beautiful feature of signals which will record all the actions performed on particular model. In the current blog post we’ll learn how …

Continue Reading...
Django Custom Management Commands

In Django project, We could manage by executing some commands which could be invoked through the manage.py.

For example:
# Sync database
python manage.py syncdb

# Start …

Continue Reading...
Understanding 'GenericForeignKey' in Django

In some cases the we might want to store generic model object, rather a particular specific model as 'ForeignKey'. Generic model object means adding a …

Continue Reading...
Basics of Django messages framework

In any web application we need to display notification messages to the end user after processing a form or some other types of his requests. …

Continue Reading...
Understanding Django model formsets in detail and their advanced usage.

Silmilar to the regular formsets, django also provide model formset that make it easy to work with django models. Django model formsets provide a way …

Continue Reading...
Django Raw Sql Queries

When your model query API don't go well or you want more performance, you can use raw sql queries in django. The Django Object Relational …

Continue Reading...
Facebook integration in your website

Using Facebook integration, we can get the user verified email id, general information, friends, pages, groups and you can post on his profile, facebook pages, …

Continue Reading...
Basics of Django templates

Django template engine comes as part of django framework and its very easy, extensible and handy to develop complex web applications with simplest efforts. Lets …

Continue Reading...
Django Model managers and properties

Django model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, …

Continue Reading...
Add captcha to django web page using Python-reCaptcha

Python-reCaptcha is a pythonic and well-documented reCAPTCHA client that supports all the features of the remote API to generate and verify CAPTCHA challenges. To add …

Continue Reading...
Django Forms basics explained

Django forms is powerful module to help django application development in rendering html from model, validate input from http request to model specifications. And we …

Continue Reading...
Creating Django App

Django is a high-level, free and open-source Python Web framework that encourages rapid development. Django follows the model–view–controller (MVC) architectural pattern. Django's primary goal is …

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties