Skip to content

Instantly share code, notes, and snippets.

@nspo
Last active March 31, 2018 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nspo/5284c4babf1ef474a412d8cd7036d6e6 to your computer and use it in GitHub Desktop.
Save nspo/5284c4babf1ef474a412d8cd7036d6e6 to your computer and use it in GitHub Desktop.
Export object_list of a django-filters FilterView to 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment