How to Create Django Admin List Actions - Apply 10% discount and Export to csv
All Django Admin list views already a default action Delete selected.
In this short tutorial I will show how create your own list actions.
Database Table
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title VARCHAR (50),
publication_date DATE,
author VARCHAR (30),
price DECIMAL,
pages INTEGER (11),
book_type INTEGER
);
models.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #models.py from django.db import models class Book(models.Model): FANTASY = 1 MYSTERY = 2 ROMANCE = 3 BOOK_TYPES = ( (FANTASY, 'Fantasy' ), (MYSTERY, 'Mystery' ), (ROMANCE, 'Romance' ), ) title = models.CharField(max_length = 50 ) publication_date = models.DateField(null = True ) author = models.CharField(max_length = 30 , blank = True ) price = models.DecimalField(max_digits = 5 , decimal_places = 2 ) pages = models.IntegerField(blank = True , null = True ) book_type = models.PositiveSmallIntegerField(choices = BOOK_TYPES) class Meta: db_table = 'books' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #admin.py from django.contrib import admin import decimal, csv from django.http import HttpResponse from django.db.models import F from myapp.models import Book def export_books(modeladmin, request, queryset): response = HttpResponse(content_type = 'text/csv' ) response[ 'Content-Disposition' ] = 'attachment; filename="books.csv"' writer = csv.writer(response) writer.writerow([ 'Title' , 'Publication Date' , 'Author' , 'Price' , 'Pages' , 'Book Type' ]) books = queryset.values_list( 'title' , 'publication_date' , 'author' , 'price' , 'pages' , 'book_type' ) for book in books: writer.writerow(book) return response export_books.short_description = 'Export to csv' class BookAdmin(admin.ModelAdmin): list_display = [ 'title' , 'publication_date' , 'author' , 'price' , 'book_type' ] actions = [ 'apply_discount' , export_books] def apply_discount( self , request, queryset): queryset.update(price = F( 'price' ) * decimal.Decimal( '0.9' )) apply_discount.short_description = 'Apply 10%% discount' admin.site.register(Book, BookAdmin) |