Search code examples
djangodjango-viewsdjango-templatesexport-to-csvdjango-filters

django: download filtered data as csv


Hej!

I want to download my data as a csv file. My problem is that I can't get my filters applyed in the downloaded csv, it'll always give me the whole list.

I tried to connect the two functions but it doesn't work as expected. But they both run fine on their own.

Does anyone know how to achieve that? Or knows what I'm doing wrong?

Any help is appreciated! :)

# views.py

def download_csv(request):
    institutions = Institution.objects.all()
    filter = InstitutionFilter(request.GET, queryset=institutions).qs

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="institutions.csv"'

    writer = csv.writer(response)

    writer.writerow(['Name', "Abbreviation", "Parent Institution", "Phone Number"])

    for institution in filter.values_list('name', 'abbreviation', 'parent_institution__name', 'contact_details'):
        writer.writerow(institution)

    return response
# filters.py

class InstitutionFilter(django_filters.FilterSet):

    name = CharFilter(field_name="name", lookup_expr="icontains")

    class Meta:
        model = Institution
        fields = "__all__"

Solution

  • I had to add the filter parameter to the url to get them working. So the solution lies in the template rather then in the views :)

    <div class="col">
                <a href="{% url 'csv_download:download_institutions' %}?{{ request.GET.urlencode }}">Download CSV</a>
    </div>
    

    EDIT:

    #csv_download/urls.py
    app_name = "csv_download"
    urlpatterns = [
        path("export-institution/", download_csv_institution, name="download_institutions"),
    ]
    
    # general urls.py
    
    urlpatterns = [
        path("admin/", admin.site.urls, name="admin"),  # admin site
        path("download_csv/", include("csv_download.urls")),  # download app
    ]