File: views.py

package info (click to toggle)
django-tables 2.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,752 kB
  • sloc: python: 7,120; makefile: 132; sh: 74
file content (59 lines) | stat: -rw-r--r-- 2,420 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from .export import TableExport


class ExportMixin:
    """
    Support various export formats for the table data.

    `ExportMixin` looks for some attributes on the class to change it's behavior:

    Attributes:
        export_class (TableExport): Allows using a custom implementation of `TableExport`.
        export_name (str): is the name of file that will be exported, without extension.
        export_trigger_param (str): is the name of the GET attribute used to trigger
            the export. It's value decides the export format, refer to
            `TableExport` for a list of available formats.
        exclude_columns (iterable): column names excluded from the export.
            For example, one might want to exclude columns containing buttons from
            the export. Excluding columns from the export is also possible using the
            `exclude_from_export` argument to the `.Column` constructor::

                class Table(tables.Table):
                    name = tables.Column()
                    buttons = tables.TemplateColumn(exclude_from_export=True, template_name=...)
        export_formats (iterable): export formats to render a set of buttons in the template.
        dataset_kwargs (dictionary): passed as `**kwargs` to `tablib.Dataset` constructor::

            dataset_kwargs = {"tite": "My custom tab title"}
    """

    export_class = TableExport
    export_name = "table"
    export_trigger_param = "_export"
    exclude_columns = ()
    dataset_kwargs = None

    export_formats = (TableExport.CSV,)

    def get_export_filename(self, export_format):
        return f"{self.export_name}.{export_format}"

    def get_dataset_kwargs(self):
        return self.dataset_kwargs

    def create_export(self, export_format):
        exporter = self.export_class(
            export_format=export_format,
            table=self.get_table(**self.get_table_kwargs()),
            exclude_columns=self.exclude_columns,
            dataset_kwargs=self.get_dataset_kwargs(),
        )

        return exporter.response(filename=self.get_export_filename(export_format))

    def render_to_response(self, context, **kwargs):
        export_format = self.request.GET.get(self.export_trigger_param, None)
        if self.export_class.is_valid_format(export_format):
            return self.create_export(export_format)

        return super().render_to_response(context, **kwargs)