Login

Admin action for a "CSV Export" with ManyToManyField

Author:
CarlosRodriguez
Posted:
June 25, 2014
Language:
Python
Version:
1.6
Score:
2 (after 3 ratings)

Based on #2369

Save the snippet as actions.py within your django app, and then add an action on any model you want in it's ModelAdmin definition.

Example usage:

from actions import export_as_csv_action

class YourModelAdmin(admin.ModelAdmin):
    list_display = (...)
    list_filter = [...]
    actions = [export_as_csv_action("CSV Export", fields=[...])]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import csv
from django.http import HttpResponse
from setuptools.compat import unicode


def export_as_csv_action(description="Export selected objects as CSV file",
						 fields=None, exclude=None, header=True):
	"""
	This function returns an export csv action
	'fields' and 'exclude' work like in django ModelForm
	'header' is whether or not to output the column names as the first row
	"""

	from itertools import chain

	def export_as_csv(modeladmin, request, queryset):
		"""
		Generic csv export admin action.
		based on http://djangosnippets.org/snippets/2369/
		"""
		opts = modeladmin.model._meta
		field_names = set([field.name for field in opts.fields])
		many_to_many_field_names = set([many_to_many_field.name for many_to_many_field in opts.many_to_many])
		if fields:
			fieldset = set(fields)
			field_names = field_names & fieldset
		elif exclude:
			excludeset = set(exclude)
			field_names = field_names - excludeset

		response = HttpResponse(content_type='text/csv')
		response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')

		writer = csv.writer(response)
		if header:
			writer.writerow(list(chain(field_names, many_to_many_field_names)))
		for obj in queryset:
			row = []
			for field in field_names:
				row.append(unicode(getattr(obj, field)))
			for field in many_to_many_field_names:
				row.append(unicode(getattr(obj, field).all()))

			writer.writerow(row)
		return response
	export_as_csv.short_description = description
	return export_as_csv

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.