sshell
sshell

Reputation: 33

How to export a csv from a search result in Django

I have a search form using django-filters and I want to export out a .csv with the filtered result. Currently it is giving me a full page of data and I am not sure how to join the 2 views together to utilize the filtering.

models.py

class account(models.Model):
    Price = models.DecimalField('price', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2)
    User = models.CharField('user', max_length=120, blank=True, null=True,)
    Account_Number = models.CharField('account Number', max_length=20, blank=True, null=True,)
    Date = models.DateField(default=now)

views.py

def stage(request):
    slist = account.objects.all()
    search_list = account.objects.all()
    search_filter = stageFilter(request.GET, queryset=search_list)
    return render(request, 'stage.html', {'slist': slist, 'search': search_filter})

def export_csv(request):
    employees = account.objects.all()
    response = HttpResponse(content_type='text/csv')  
    response['Content-Disposition'] = 'attachment; filename="file.csv"'  
    writer = csv.writer(response)
    writer.writerow (['User', 'Account Number', 'Price', 'Date'])
    for employee in employees:  
        writer.writerow([employee.User,employee.Account_Number,employee.Price, employee.Date])  
    return response

filters.py

class stageFilter(django_filters.FilterSet):
    Date = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={'type': 'date'}))

class Meta:
    model = account
    fields = ['User', 'Account_Number', 'Price', 'Date']

urls.py

urlpatterns = [
    path('stage/', views.stage, name='stage'),
    path('export_csv', views.export_csv, name='exportcsv')
]

Upvotes: 0

Views: 2070

Answers (1)

sshell
sshell

Reputation: 33

This is the fix for my issue. I obviously needed to incorporate the search/queryset in to the export_csv definition, which I had already tried but it failed. The missing piece of the code was to add request.GET.urlencode() in to the template, which takes the query string from the url and passes the result in to the .csv

views.py

def export_csv(request):
    employees = account.objects.all()
    search = stageFilter(request.GET, queryset=employees).qs
    response = HttpResponse(content_type='text/csv')  
    response['Content-Disposition'] = 'attachment; filename="file.csv"'  
    writer = csv.writer(response)
    writer.writerow (['User', 'Account Number', 'Price', 'Date'])
    for e in search.values_list('User', 'Account_Number', 'Price', 'Date'):
        writer.writerow(e)  
    return response

html

<table class="table table-striped table-bordered table-hover">
  <thead class="table-dark">

    <thead>
        <tr>
            <th>User</th>
            <th>Account Number</th>
            <th>Price</th>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            {% for item in search.qs%}

            <td>{{item.User}}</td>
            <td>{{item.Account_Number}}</td>
            <td>{{item.Price}}</td>
            <td>{{item.Date}}</td>
        </tr>
          {% endfor %}
       
    </tbody>
</table>

<div><a href="{% url 'exportcsv' %}?{{request.GET.urlencode}}">
<button type="button" class="button">Export to CSV</button></a></div>

Upvotes: 2

Related Questions