0.4.4: Django 3.0 support, actions.export_as_csv_action added.
[fnpdjango.git] / fnpdjango / actions.py
diff --git a/fnpdjango/actions.py b/fnpdjango/actions.py
new file mode 100644 (file)
index 0000000..ec0479e
--- /dev/null
@@ -0,0 +1,51 @@
+# Source: https://gist.github.com/jeremyjbowers/e8d007446155c12033e6
+from __future__ import unicode_literals
+
+import csv
+from django.http import HttpResponse
+
+try:
+    unicode
+except NameError:
+    pass
+else:
+    str = 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
+    """
+    def export_as_csv(modeladmin, request, queryset):
+        """
+        Generic csv export admin action.
+        based on http://djangosnippets.org/snippets/1697/
+        """
+        opts = modeladmin.model._meta
+        field_names = [field.name for field in opts.fields]
+
+        if fields:
+            for f in fields:
+                if f not in field_names:
+                    field_names.append(f)
+
+        elif exclude:
+            field_names = [f for f in field_names if f not in exclude]
+
+        response = HttpResponse(content_type='text/csv')
+        response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
+
+        writer = csv.writer(response)
+
+        if header:
+            writer.writerow(field_names)
+        for obj in queryset:
+            writer.writerow([str(getattr(obj, field)) for field in field_names])
+
+        return response
+
+    export_as_csv.short_description = description
+    return export_as_csv
+