Skip to content

Commit

Permalink
feat(generic): add export support to list views
Browse files Browse the repository at this point in the history
  • Loading branch information
gythaogg committed Jan 28, 2025
1 parent 21c2192 commit 1db7584
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
12 changes: 11 additions & 1 deletion apis_core/generic/templates/generic/generic_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
{% load crispy_forms_tags %}
{% load generic %}
{% load core %}
{% load export_url from django_tables2 %}
{% if filter %}

{% block col %}
Expand Down Expand Up @@ -39,7 +40,16 @@
{% block additionalcols %}
<div class="col-8">
<div class="card">
<div class="card-header">{{ table.paginator.count }} results</div>
<div class="card-header">{{ table.paginator.count }} results.
{% if view.export_formats %}
Download {% for format in view.export_formats %}
<a href="{% export_url format %}">
{{ format | upper}}
</a>
{% if not forloop.last %} | {% endif %}
{% endfor %}
{% endif %}
</div>
<div class="card-body">

{% block table %}
Expand Down
14 changes: 14 additions & 0 deletions apis_core/generic/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import namedtuple
from copy import copy
from datetime import datetime

from dal import autocomplete
from django import forms, http
Expand All @@ -21,6 +22,7 @@
from django_filters.views import FilterView
from django_tables2 import SingleTableMixin
from django_tables2.columns import library
from django_tables2.export.views import ExportMixin
from django_tables2.tables import table_factory

from apis_core.apis_metainfo.models import Uri
Expand Down Expand Up @@ -100,6 +102,7 @@ def get_permission_required(self):
class List(
GenericModelMixin,
PermissionRequiredMixin,
ExportMixin,
SingleTableMixin,
FilterView,
):
Expand All @@ -123,6 +126,17 @@ def get_table_class(self):
table_class = first_member_match(table_modules, GenericTable)
return table_factory(self.model, table_class)

export_formats = ["csv", "json"]

def get_export_filename(self, extension):
table_class = self.get_table_class()
if hasattr(table_class, "export_filename"):
filename = table_class.export_filename
else:
now = datetime.now()
filename = f"{table_class.__name__}_{now.strftime('%Y-%m-%d_%H-%M-%S')}"
return f"{filename}.{extension}"

def get_table_kwargs(self):
kwargs = super().get_table_kwargs()

Expand Down

0 comments on commit 1db7584

Please sign in to comment.