简体   繁体   中英

Django: export csv file with django_table2

I want to have an download button a html page that renders a django table.

I followed the documentation of django2 and this post How to export.csv with Django-Tables2? was helpful but could not make the trick.

I feel like I have done everything correctly (according to my beginner skills), there is no error but the download button is not there.

I was wondering if someone has any help to provide on this one

table.py

class AnormalTable(tables.Table):

    class Meta:
        model = stock_anormal
        template_name = "django_tables2/bootstrap4.html"
        export_formats = ['csv', 'xlsx']

view.py

@method_decorator(login_required, name='dispatch')
class PostDetailalerte_negat(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin):
    def get(self, request):
        queryset = stock_negatif.objects.all()
        table =  NegatTable(queryset)

        RequestConfig(request).configure(table)
        export_format = request.GET.get("_export", None)
        if TableExport.is_valid_format(export_format):
            exporter = TableExport(export_format, table)
            return exporter.response("table.{}".format(export_format))


        return render(request, 'detailstocknegat.html', {'table':table})

html snipet

 <div class="d-sm-flex align-items-center justify-content-between mb-4">
                    <h1 class="h3 mb-0 text-gray-800">ITEMS IN ALERTE SAFETY STOCK LEVEL</h1>
              <div>
                  {% for format in view.export_formart %}
                      <a href="{% export_url "csv" %}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a>
                       {%  endfor %}
              </div>
              </div>
              <table>
                   {% load django_tables2 %}
                {% render_table table %}


              </table>

I'm not sure if this will fix this specific problem but I ran into basically the same issue and this is how I solved it:

I moved the export_formats = ['csv', 'xlsx'] that was in table.py originally into the view for my table (view.py in this example). Then I passed export_formats directly to the html by changing the return code in views.py: return render(request, 'detailstocknegat.html', {'table':table, 'export_formats':export_formats}) . Then in the html for my table (html snipet in this example) I changed the for statement to be:

{%for format in export_formats %}>
      <a href="{% export_url format %}">
      download  <code>.{{ format }}</code>
      </a>
{% endfor %}

I hope this helps somebody out there!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM