Adding custom actions to the administration site

Django offers you a wide range of options to customize the administration site. We are going to modify the object list view to include a custom admin action.

An admin action works as follows: a user selects objects from the admin's object list page with checkboxes, then selects an action to perform on all of the selected items, and executes the action. The following screenshot shows where actions are located in the administration site:

Create custom admin actions to allow staff users to apply actions to multiple elements at once.

You can create a custom action by writing a regular function that receives the following parameters:

  • The current ModelAdmin being displayed
  • The current request object as an HttpRequest instance
  • A QuerySet for the objects selected by the user

This function will be executed when the action is triggered from the administration site.

We are going to create a custom admin action to download a list of orders as a CSV file. Edit the admin.py file of the orders application and add the following code before the OrderAdmin class:

import csv
import datetime
from django.http import HttpResponse

def export_to_csv(modeladmin, request, queryset):
opts = modeladmin.model._meta
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;'
'filename={}.csv'.format(opts.verbose_name)
writer = csv.writer(response)

fields = [field for field in opts.get_fields() if not field.many_to_many
and not field.one_to_many]
# Write a first row with header information
writer.writerow([field.verbose_name for field in fields])
# Write data rows
for obj in queryset:
data_row = []
for field in fields:
value = getattr(obj, field.name)
if isinstance(value, datetime.datetime):
value = value.strftime('%d/%m/%Y')
data_row.append(value)
writer.writerow(data_row)
return response
export_to_csv.short_description = 'Export to CSV'

In this code, we perform the following tasks:

  1. We create an instance of HttpResponse, including a custom text/csv content type, to tell the browser that the response has to be treated as a CSV file. We also add a Content-Disposition header to indicate that the HTTP response contains an attached file.
  2. We create a CSV writer object that will write on the response object.
  3. We get the model fields dynamically using the get_fields() method of the model _meta options. We exclude many-to-many and one-to-many relationships.
  4. We write a header row including the field names.
  1. We iterate over the given QuerySet and write a row for each object returned by the QuerySet. We take care of formatting datetime objects because the output value for CSV has to be a string.
  2. We customize the display name for the action in the template by setting a short_description attribute to the function.

We have created a generic admin action that can be added to any ModelAdmin class.

Finally, add the new export_to_csv admin action to the OrderAdmin class as follows:

class OrderAdmin(admin.ModelAdmin):
# ...
actions = [export_to_csv]

Open http://127.0.0.1:8000/admin/orders/order/ in your browser. The resulting admin action should look like this:

Select some orders and choose the Export to CSV action from the select box, then click the Go button. Your browser will download the generated CSV file named order.csv. Open the downloaded file using a text editor. You should see content with the following format, including a header row and a row for each Order object you selected:

ID,first name,last name,email,address,postal code,city,created,updated,paid,braintree id 
3,Antonio,MelĂ©,[email protected],Bank Street,WS J11,London,25/02/2018,25/02/2018,True,2bwkx5b6
...

As you can see, creating admin actions is pretty straightforward. You can learn more about generating CSV files with Django at https://docs.djangoproject.com/en/2.0/howto/outputting-csv/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset