Last active
March 31, 2018 20:32
-
-
Save nspo/5284c4babf1ef474a412d8cd7036d6e6 to your computer and use it in GitHub Desktop.
Export object_list of a django-filters FilterView to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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