How To Add Custom Django Admin Actions

In this article we  explain how to add custom django admin action. Let's say that we have model called Products which have status Available and Not Available and we want to  have options in  django Admin to change status  in Available or Not available ..

 

 

In models.py we have :

 

STATUS_CHOICHES=(
    ('ava','Available'),
    ('not','Not Available'),
    )

class Products(models.Model):
    name=models.CharField(max_length=100)
    status=models.CharField(max_length=3,choices=STATUS_CHOICHES)

    class Meta:
        verbose_name_plural="MY PRODUCTS"

 

Syncronize your database .

python manage.py syncdb

if you're using south , then

python manage.py schemamigration <app_name> --auto

python manage.py migrate <app_name>

 

if you're using Django1.7

python manage.py makemigrations
python manage.py migrate

 

STATUS_CHOICHE - An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. Read more ..

verbose_name_plura - The plural name for the object.. Read more

Then we will add custom actions for our model . You should add in admin.py

 

def available (modeladmin,request,queryset):
    queryset.update(status='ava')

def not_available (modeladmin,request,queryset):
    queryset.update(status='not')

class ProductsAdmin(admin.ModelAdmin):
    list_display=('name','id','status')
    actions=[available,not_available]
admin.site.register(Products,ProductsAdmin)

 

Now, you'll have two new option in Django admin avaialble and available ..if you have any question feel free to  ask ..

email@djangotutsme.com Dec. 23, 2014, 12:36 p.m.