Matt Wilson
Matt Wilson

Reputation: 49

Add link on a web page to export tables2 data in Django

I'm trying to include a link on a webpage to download a tables2 table to csv. I got the commented out piece below from the documentation, and I think it might just need a simple tweak to get it to work with my code. Any thoughts?

views.py

class PlatListView(SingleTableMixin, FilterView):
    model = Plat
    template_name = 'blog/filtertable.html'
    filter_class = PlatFilter

    def get_context_data(self, **kwargs):
        context = super(PlatListView, self).get_context_data(**kwargs)
        query = Phase.objects.all().select_related('plat','plat__community')
        
        f = PlatFilter(self.request.GET, queryset=query)
        
        t = PlatTable(data = f.qs)

        RequestConfig(self.request, paginate=False).configure(t)
        
            
        context['filter'] = f
        context['table'] = t
        '''
        export_format = self.request.GET.get("_export", None)
        if TableExport.is_valid_format(export_format):
            exporter = TableExport(export_format, query)
            return exporter.response("query.{}".format(export_format))
        '''
        return context

filtertable.html

{% extends "blog/base.html" %}
{% block content %}



{% load querystring from django_tables2 %}
<div style = 'padding-top: 24px'>
    <a href="{% querystring '_export'='csv' %}">Download CSV</a>
</div>


{% load render_table from django_tables2 %}
{% load bootstrap4 %}

{% if filter %}
    <form action="" method="get" class="form form-inline">
        {% bootstrap_form filter.form layout='inline' %}
        {% bootstrap_button 'filter' %}
    </form>
{% endif %}
{% render_table table 'django_tables2/bootstrap4.html' %}

{% endblock content %}

Upvotes: 0

Views: 299

Answers (1)

fekioh
fekioh

Reputation: 996

The commented-out snippet in your code is for function-based views as mentioned in the docs. In your case you should just add the ExportMixin :

from django_tables2.export.views import ExportMixin

class PlatListView(SingleTableMixin, ExportMixin, FilterView):
    # other stuff your view is doing

Upvotes: 1

Related Questions