Created
April 22, 2016 19:29
-
-
Save bozdoz/8e80aa119dc77462f52dcaa9edecdeaa to your computer and use it in GitHub Desktop.
Django Admin : Action for Exporting User details to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ] | |
# ... |
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
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
For information!!!
In Django 1.11
FileWrapper is moved to wsgiref.util
from wsgiref.util import FileWrapper