Monday 16 May 2016

Django Admin Action

Django Admin Action
   If you are looking for a way to update for change many objects at once via admin panel then the best way is to use Django's admin action. By setting a custom action you can change the object list in the admin by selecting the objects you want to change and go to the bottom of the page where you can see a drop down. Click on the drop down and it will show a list of admin action including the custom action that you have created. By default you can see 'Delete Selected User' action.

Creating Sample Model

Lets create a sample table in models.py to.
 
from django.db import models

class ProductsUpdated(models.model):
    '''
    Model for storing the product basic updation details.
    '''
    name = models.CharField(max_length=250)
    price = models.FloatField(default=0.0)
    updated = models.BooleanField(default=False)

  def __unicode__(self):
       return self.name


Writing Custom Action

In admin.py
 
from django.contrib import admin

def updated(modeladmin, request, queryset):
    '''
    Custom action method
    '''
    queryset.update(updated=True)           # Updating the 'úpdated' field
updated.short_description="Items Updated"   # Description thats shown in the bottom drop down


Now call the action method in the admin of the table ProductsUpdated.
The whole code would look like this:


from django.contrib import admin
from myapp.models import ProductsUpdated

def updated(modeladmin, request, queryset):     queryset.update(updated=True) updated.short_description =  "Items Updated"
def ProductsUpdatedAdmin(admin.ModelAdmin):     list_display = [ 'title', 'úpdated']     action = [updated] admin.site.register(ProductsUpdated, ProductsUpdatedAdmin)