Skip to content

Instantly share code, notes, and snippets.

@bozdoz
Created April 22, 2016 19:29
Show Gist options
  • Save bozdoz/8e80aa119dc77462f52dcaa9edecdeaa to your computer and use it in GitHub Desktop.
Save bozdoz/8e80aa119dc77462f52dcaa9edecdeaa to your computer and use it in GitHub Desktop.
Django Admin : Action for Exporting User details to CSV
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
def export_to_csv (modeladmin, request, queryset):
import csv, StringIO
from django.core.servers.basehttp import FileWrapper
cols = ['username','email','first_name','last_name']
# get qs values
data = list( queryset.values_list(*cols) )
if not data:
messages.error(request, 'No data to export')
return HttpResponseRedirect( request.get_full_path() )
# create empty csv
csv_file = StringIO.StringIO()
csv_writer = csv.writer(csv_file, quoting = csv.QUOTE_ALL)
# add headers
csv_writer.writerow( cols )
# add qs values
for row in data:
csv_writer.writerow( [s.encode('utf-8') for s in row] )
csv_file.flush()
csv_file.seek(0)
response = HttpResponse(FileWrapper( csv_file ), content_type='text/csv')
response['Content-Disposition'] = "attachment; filename=user-csv-export.csv"
return response
export_to_csv.short_description = "Export to CSV"
class UserProfileAdmin(UserAdmin):
actions = [ export_to_csv ]
# ...
@lexnjugz
Copy link

You might also what to include the below piece of code inorder for it to work with python3
try:
from StringIO import StringIO
except ImportError:
from io import StringIO

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

@rikoz
Copy link

rikoz commented Sep 25, 2020

Please my exported csv list comes with a 'b' prepended to each value. How can I fix this?? Also how can I get only unique values from db

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment