django-tables2 Documentation

repository·master·Indexed 24 days ago

https://github.com/jieter/django-tables2

A table and data-grid framework for Django that simplifies converting datasets, including Django QuerySets, into HTML tables. It features built-in support for pagination, sorting, and model-based generation, providing a UI that does not rely on JavaScript. The library includes a variety of specialized Column types, generic view mixins like SingleTableView and MultiTableMixin, and a LazyPaginator to efficiently handle large datasets by avoiding expensive count queries.

Tokens
21.4K
Snippets
71
Records
114
Agent score
83%

What's inside django-tables2

  1. Overview of django-tables2 features

    master

    django-tables2 is a Django application designed to transform data into HTML tables, similar to how django.forms handles HTML forms.

    Key capabilities include:

    • Data Sources: Supports any iterable, with specialized support for Django QuerySets.
    • Automatic Generation: Can automatically generate tables based on Django models.
    • Customization: Supports custom column functionality through subclassing.
    • Built-in UI: Features a UI that does not rely on JavaScript.
    • Interactivity: Native support for pagination and column-based table sorting.
    • Integration: Provides a template tag for trivial HTML rendering and a generic view mixin for easy integration into Django views.
  2. Use Accessors to traverse nested data

    master

    An accessor is a double-underscore (__) separated path used to define how a column retrieves data from a record. This allows you to traverse dictionaries, attributes, or lists to reach nested values.

    When an accessor is used, the library attempts lookups in this order:

    1. Dictionary lookup: a[b]
    2. Attribute lookup: a.b
    3. List index lookup: a[int(b)]

    If the resolved value is a callable, it will be executed and its return value used. You can apply an accessor to a tables.Column to pull nested data directly into a column.

    >>> from django_tables2 import A
    >>> data = {"abc": {"one": {"two": "three"}}}
    >>> A("abc__one__two").resolve(data)
    'three'
    
    # Using accessor in a Table
    class MyTable(tables.Table):
        abc = tables.Column(accessor="abc__one__two")
    
    data = [{"abc": {"one": {"two": "three"}}}, {"abc": {"one": {"two": "four"}}}]
    table = MyTable(data)
    # table.rows[1] will contain 'four'
  3. Use a custom template for full rendering control

    master
    If the built-in templates do not meet your requirements, you can take full control of the rendering process. Instead of using the default rendering logic, pass your Table subclass instance into your own custom Django template and render the table components manually. It is recommended to use one of the provided django-tables2 templates as a starting point for your custom template.
  4. Customize exported values for columns

    master

    The export process uses the .Table.as_values() method. By default, this calls the value() method of each column, which in turn calls render().

    If your render_foo method produces HTML (like links or buttons) that you do not want in your export, you should override the value_foo method to return the raw data value instead.

  5. Configure global settings with Table.Meta

    master

    Use the Table.Meta inner class to define global settings for a table class. This is preferred over passing arguments to the constructor when you want the settings to apply to every instance of that table type.

    Important Inheritance Rule: When subclassing a table that already has a Meta class, you must specify the parent's Meta as the base for the child's Meta to ensure settings are inherited. Note that all attributes defined in the child's Meta will overwrite the parent's attributes; they are not merged.

    class PersonTable(tables.Table):
        class Meta:
            model = Person
            exclude = ("email", )
    
    class PersonWithEmailTable(PersonTable):
        class Meta(PersonTable.Meta):
            exclude = ()  # This clears the exclusion from the parent
    class PersonWithEmailTable(PersonTable):
        class Meta(PersonTable.Meta):
            exclude = ()
  6. Use `Table.value_foo` for non-HTML data exports

    master
    If you use Table.as_values to export data (e.g., to JSON or CSV), render_foo methods will not be used because they are intended for HTML output. Instead, define value_foo methods. These are analogous to render_foo but are used to determine the raw value used during data export.
  7. How to contribute columns via Table Mixins

    master

    When creating a mixin intended to add columns to a table, the mixin must be a subclass of django_tables2.tables.Table.

    If a mixin is a plain class (not inheriting from Table), any Column instances defined within it will be ignored by the final table class. To ensure columns are correctly registered in the table's base_columns, inherit the mixin from tables.Table.

    # INCORRECT: Columns in a plain class mixin are not added to the table
    class UselessMixin:
        extra = tables.Column()
    
    class TestTable(UselessMixin, tables.Table):
        name = tables.Column()
    
    # TestTable.base_columns.keys() will only contain ['name']
    
    
    # CORRECT: Inherit from tables.Table to contribute columns
    class UsefulMixin(tables.Table):
        extra = tables.Column()
    
    class TestTable(UsefulMixin, tables.Table):
        name = tables.Column()
    
    # TestTable.base_columns.keys() will contain ['extra', 'name']
  8. Use inheritance to build Tables that share features

    master

    You can use standard Python class inheritance to build tables that share column definitions.

    • Subclasses inherit all columns from the base class.
    • To remove a column from a subclass, overwrite the column attribute with None.
    import django_tables2 as tables
    
    class CountryTable(tables.Table):
        name = tables.Column()
        language = tables.Column()
    
    # Inherits 'name' and 'language'
    class TouristCountryTable(CountryTable):
        tourist_info = tables.Column()
    
    # Only shows 'name' because 'language' is set to None
    class SimpleCountryTable(CountryTable):
        language = None
  9. Include or exclude columns from export

    master

    You can control which columns appear in an export using several methods:

    1. Include hidden columns: Use visible=False on a column definition to keep it in the export while hiding it from the HTML table.
    2. Exclude columns in Table definition: Use exclude_from_export=True on a column.
    3. Exclude columns in TableExport instance: Pass a tuple to the exclude_columns argument when creating TableExport.
    4. Exclude columns in ExportMixin: Add an exclude_columns attribute to your view class.
    # 1. Using visible=False to include in export but hide in HTML
    class Table(tables.Table):
        first_name = columns.Column(visible=False)
    
    # 2. Using exclude_from_export=True in Table definition
    class Table(tables.Table):
        buttons = columns.TemplateColumn(template_name="...", exclude_from_export=True)
    
    # 3. Excluding via TableExport instance
    exporter = TableExport("csv", table, exclude_columns=("image", "buttons"))
    
    # 4. Excluding via ExportMixin in a view
    class TableView(ExportMixin, tables.SingleTableView):
        table_class = MyTable
        exclude_columns = ("buttons", )