pythondjangodjango-viewscsv-write-stream

How to include a dropdown query into a HttpResponse view


I would like to convert to excel contents of a model after passing a filter from the dropdown selection . Here is the view.

def ConvertToExcelView(request):
    response = HttpResponse(content_type='text/csv')
    writer = csv.writer(response)
    writer.writerow([('name'), ('adm'),('form'),('stream') ])
    for member in Marks.objects.filter(student__school__name=request.user.school).values_list('student__name',     'student__adm', 'student__klass__name', 'student__stream__name':
        writer.writerow(member)       
    response['Content-Disposition'] = 'attachment; filename="members.csv"'
    return response

Is there a way I can incorporate this into the view????

query = request.GET.get('view_classes')
    if query:
        queryset = (Q(student__klass__name__icontains = query))            
    return render(request,'students_marks.html',all_mark_results)

Please ask for more clarifications incase I'm not clear with this.


Solution

  • This is fairly simple. Simply include the get request and give a name to the form you intend to get the selection from i.e.

    def ConvertToExcelView(request):
        details = request.GET.get('s_details') #Assuming the form name is s_details
        queryset = (Q(student__klass__name__exact = details))
        response = HttpResponse(content_type='text/csv')
        writer = csv.writer(response)
        writer.writerow([('name'), ('adm'),('form'),('stream') ])
        for member in Marks.objects.filter(queryset).distinct().filter(student__school__name=request.user.school).values_list('student__name',     'student__adm', 'student__klass__name', 'student__stream__name':
            writer.writerow(member)       
        response['Content-Disposition'] = 'attachment; filename="members.csv"'
        return response
    

    This will work like charm. Revert if there are explanations you need.