Commits

Anonymous committed 9dddae9

Added "export as CSV" admin action

Comments (0)

Files changed (1)

+from django.contrib.contenttypes import generic
+from gnocchi2.tools import models
+from django.http import HttpResponse
+import csv
+
+class InlineAttributeAdmin( generic.GenericTabularInline ):
+    model = models.Attribute
+    ct_field = 'content_type'
+    ct_fk_field = 'object_id'
+
+##
+## Model "export to CSV" tool
+##
+from django.core.serializers.python import Serializer
+
+class CsvSerializer(Serializer):
+    def start_serialization(self):
+        self.csv = csv.DictWriter(self.stream, fieldnames=self.selected_fields)
+        if self.options.get('headers', True):
+            self.csv.writerow(dict((x,x) for x in self.selected_fields))
+        self._current = None
+
+    def end_object(self, obj):
+        self._current[obj._meta.pk.name] = obj.pk
+        self.csv.writerow(self._current)
+        self._current = None
+
+    def getvalue(self):
+        return self.stream
+
+def export_as_csv(admin, request, queryset):
+    fields = getattr(admin, 'csv_fields', None)
+    filename = getattr(admin, 'csv_filename', '%s_export.csv' % admin.model._meta.module_name)
+    response = HttpResponse(mimetype='text/csv')
+    response['Content-Disposition'] = 'attachment; filename=%s' % filename
+    if fields is None:
+        fields = [field.name for field in admin.model._meta.local_fields]
+    xout = CsvSerializer()
+    return xout.serialize(queryset, fields=fields, stream=response)
+
+export_as_csv.short_description = 'Export as CSV'