Django Admin Project: How to Add Custom ‘Actions’ (Export to CSV)

3D visualization of a custom lever on a dashboard converting selected user records into a CSV file, representing Django Admin actions.

You’ve customized your Django Admin, but it has a hidden power: “Actions.” An action is a function you can run on all selected items in the admin list.

Let’s build the most useful action: “Export selected items to CSV. Django Admin Actions make this type of bulk export possible out of the box.

Step 1: The Action Function

An action is just a Python function that takes 3 arguments: (modeladmin, request, queryset). We’ll write one for our Post model.

pages/admin.py

import csv
from django.http import HttpResponse

def export_as_csv(modeladmin, request, queryset):
    """A custom action to export selected Posts to a CSV."""
    
    # 1. Set up the HttpResponse
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="posts.csv"'
    
    # 2. Create a CSV writer
    writer = csv.writer(response)
    
    # 3. Write the header row
    writer.writerow(['Title', 'Author', 'Text'])
    
    # 4. Write the data rows
    for post in queryset:
        writer.writerow([post.title, post.author.username, post.text])
        
    return response

# Give it a "nice name" for the admin dropdown
export_as_csv.short_description = "Export Selected Posts to CSV"

Step 2: Register the Action

Now, just add this function to your ModelAdmin‘s actions list.

pages/admin.py

from django.contrib import admin
from .models import Post

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
    # ... other settings ...
    
    # 4. Add the 'actions' list
    actions = [export_as_csv] # <-- Add your function here

admin.site.register(Post, PostAdmin)

Step 3: Run It!

Go to your Post list in the admin. You will now see an “Action” dropdown menu.

  1. Check the boxes for 3-4 posts.
  2. Select “Export Selected Posts to CSV” from the dropdown.
  3. Click “Go”.

Your browser will instantly download a posts.csv file with the exact data you selected!


Key Takeaways

  • Django Admin allows custom actions, enabling functions on selected items in the admin list.
  • You can create an action to ‘Export selected items to CSV’ for your Post model.
  • First, define the action function in your pages/admin.py file with appropriate arguments.
  • Next, register the action in your ModelAdmin’s actions list to make it available.
  • Finally, use the dropdown menu in the Post list to export selected posts as a CSV file.

Similar Posts

Leave a Reply