I am using django-filter and django-import-export. I can build an HTML table and filter it using django-filter just fine, but I want the user to be able to export the filtered table, not the whole table. (That is, this is not through the admin feature.)
I suspect the issue is I have one view for the list itself, but the export is in another view, and I can't seem to pass the filtered queryset to the export view, and I can't figure out how to do the export and filter on the same view. They're both GET requests. I feel like I'm missing something very very basic here.
In my app/views.py:
from django.http import HttpResponse
from django.shortcuts import render
from .filters import RoleFilter
from .models import Role
from .resources import RoleResource
from tablib import Dataset
def role_list(request):
"""list the roles and filter appropriately"""
f = RoleFilter(request.GET, queryset=Role.objects.all())
return render(request, 'app/rolelist.html', {'filter': f})
def export_filtered_roles(request):
"""export to csv"""
f = RoleFilter(request.GET, queryset=Role.objects.all())
dataset = RoleResource.export(f)
response = HttpResponse(dataset.csv, content_type="text/csv")
response['Content-Disposition'] = 'attachment;filename="roles.csv"'
return response
I can't seem to make the connection. This version of the code gives me an error: RoleFilter object has no attribute 'before-export'. I get the same error if I use dataset = RoleResource.export(f.qs)
.
Any suggestions as to how I can tie the filter to the export view?
Additional Information: Here's the template I'm using
<form method="get" action=".">
{{ filter.form.as_p }}
<input type="submit" value="Filter"/>
</form>
<table>... loops through filter.qs ...</table>
<a href="{% url 'roleexport' %}">Export Roles</a>
This is why I think there's a disconnect between the Form object and the export feature. Can I somehow control the export from the form?
This seems like a hack, but it works. All I had to do was change the link in my template:
<a href="{% url 'roleexport' %}?{{request.GET.urlencode}}">Export Roles</a>
This works for the filtered and unfiltered lists.