Skip to content

Instantly share code, notes, and snippets.

@stephenemslie
Last active December 16, 2015 08:19
Show Gist options
  • Save stephenemslie/5405123 to your computer and use it in GitHub Desktop.
Save stephenemslie/5405123 to your computer and use it in GitHub Desktop.
Export to csv action for users in the Django admin.
import csv
from django.contrib import admin
from django.http import HttpResponse
class UserAdmin(ModelAdmin):
actions = ["export_as_csv"]
def export_as_csv(self, request, queryset):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="users.csv"'
user_fields = ['id', 'date_joined', 'email', 'username']
writer = csv.DictWriter(response, user_fields)
writer.writeheader()
for user in queryset:
user_dict = {field: unicode(getattr(user, field)).encode('utf-8') for field in user_fields}
writer.writerow(user_dict)
return response
export_as_csv.short_description = "Download selected users as csv"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment