Export object_list of a django-filters FilterView to CSV
This is a simple way to allow users to export the data they have just filtered using django-filter as CSV.
# Normal View (has a link to export view and keeps GET parameters) @method_decorator(staff_member_required(login_url='user_login'), name='dispatch') class PaymentListView(FilterView): filterset_class = filters.PaymentFilter template_name = "barsys/userarea/payment_list.html" paginate_by = 10 # Export View @method_decorator(staff_member_required(login_url='user_login'), name='dispatch') class PaymentExportView(FilterView): filterset_class = filters.PaymentFilter def render_to_response(self, context, **response_kwargs): # Could use timezone.now(), but that makes the string much longer filename = "{}-export.csv".format(datetime.datetime.now().replace(microsecond=0).isoformat()) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) writer = csv.writer(response) writer.writerow(['created', 'email', 'display_name']) for obj in self.object_list: writer.writerow([obj.created_date, obj.user.email, obj.user.display_name]) return response
Leave a Reply