[Django]-Download a text/csv file from django app that populates HTML table from a database query

4πŸ‘

βœ…

In fact you are requesting the same set of data from your site. The only thing changing is the format. So normally you just want to request the same page with a GET parameter like ?format=csv. So your view function would look like this:

def from_samrun(request):    
    if request.GET:
        lab_query = request.GET['lab_number']
        var_list = VarSamRun.objects.filter(sample=lab_query)
        if request.GET['format'] == 'csv':
            response = HttpResponse('')
            response['Content-Disposition'] = 'attachment; filename=file.csv'   
            writer = csv.writer(response, dialect=csv.excel)
            writer.writerow(some_random_data_list)
            return response

        if var_list:
            return render(request, 'results/varlist.html', {'var_list': var_list,'lab_query':lab_query})
        else:
            return render(request, 'results/varlist.html', {'query': [sam_query]})
    else:
        return render(request, 'results/varlist.html' {'error': 'Error'})

And your template:

<form method='GET'>
    <input type='hidden' name='format' value='csv'>
    <input type='hidden' name='lab_query' value={{lab_query}}>
    <input type='submit'>
</form>
πŸ‘€Nerade

0πŸ‘

You can write URL route for your download action. Point it to download_view view in urls.py

πŸ‘€Shri

-1πŸ‘

Maybe the fastest solution will be plugin:
jQuery Datatables

And some easy setup for your page.

πŸ‘€Marin

Leave a comment