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! :slight_smile:

# 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__"

What does the url that you’re trying look like? (Are you passing the name parameter in as a query variable?)

app_name = "csv_download"
urlpatterns = [
    path("export/", download_csv, name="download_institutions"),
    ]

this is the url. And with the ‘normal’ download this works fine. Do I need to redirect to the path("institutions", search_institution, name="institutions") from my stakeholders app? How can I pass the parameter of the query?

I’m sorry, I meant to ask for the actual URL that you use in the browser to request this page. It should look something like http://example.com/export?name=Ken.

Ah ok.

http://127.0.0.1:8000/stakeholders/institutions?name=Helmholtz+Institut

it stays on the url and I get a pop up window

I don’t understand what you’re trying to do here. I asked for the url you’re using and you show me a url with a path of export, but this example you just posted appears to be for something different.

I never GET to the path with export. It just stays on the url of the view for the table and I only get a pop up window.

I have no idea whats happening there as they are even in different apps.

Got it going with

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

:slight_smile: