django-tables2 - An app for creating HTML tables

Overview

django-tables2 - An app for creating HTML tables

Latest PyPI version Any color you like

django-tables2 simplifies the task of turning sets of data into HTML tables. It has native support for pagination and sorting. It does for HTML tables what django.forms does for HTML forms. e.g.

Features:

  • Any iterable can be a data-source, but special support for Django QuerySets is included.
  • The builtin UI does not rely on JavaScript.
  • Support for automatic table generation based on a Django model.
  • Supports custom column functionality via subclassing.
  • Pagination.
  • Column based table sorting.
  • Template tag to enable trivial rendering to HTML.
  • Generic view mixin.

An example table rendered using django-tables2

An example table rendered using django-tables2 and bootstrap theme

An example table rendered using django-tables2 and semantic-ui theme

Example

Start by adding django_tables2 to your INSTALLED_APPS setting like this:

INSTALLED_APPS = (
    ...,
    "django_tables2",
)

Creating a table for a model Simple is as simple as:

import django_tables2 as tables

class SimpleTable(tables.Table):
    class Meta:
        model = Simple

This would then be used in a view:

class TableView(tables.SingleTableView):
    table_class = SimpleTable
    queryset = Simple.objects.all()
    template_name = "simple_list.html"

And finally in the template:

{% load django_tables2 %}
{% render_table table %}

This example shows one of the simplest cases, but django-tables2 can do a lot more! Check out the documentation for more details.

Comments
  • Duplicated table rows after sorting by column header

    Duplicated table rows after sorting by column header

    I'm experiencing an issue where some rows are rendered multiple times in place of other rows. The table in question used to render perfectly well on an earlier versions of django and django-tables2. I upgraded both of them at the same time to the latest version of each (django 1.10, django-tables2 1.2.4) then this issue started happening.

    See this image here for a demonstration: http://imgur.com/a/pPRT8

    When I load a table without choosing a sort order by the column, I don't see this issue. Once I click on a column header to change the sort order then rows are duplicated.

    So far I've identified that the data passed into the BoundRows object is correct, with no duplicated items. However iterating through the bound rows returns duplicated entries. So it looks like something may be changing the data object while the iteration is taking place.

    This issue is happening on tables of length ~150, and I haven't (yet) been able to reproduce this issue with a smaller test dataset.

    This snippet shows the test code I have used to narrow down the cause of the issue.

    --- a/django_tables2/rows.py
    +++ b/django_tables2/rows.py
    @@ -8,6 +8,7 @@ from django.utils import six
     from .columns.linkcolumn import BaseLinkColumn
     from .utils import A, AttributeDict, call_with_appropriate, computed_values
    
    +import sys
    
     class BoundRow(object):
         """
    @@ -187,9 +188,17 @@ class BoundRows(object):
         def __init__(self, data, table):
             self.data = data
             self.table = table
    +        for d in data:
    +            print >>sys.stderr, d
    +
    +        print >>sys.stderr, "end data"
    +
    
         def __iter__(self):
             for record in self.data:
    +            print >>sys.stderr, "__iter__", record
                 yield BoundRow(record, table=self.table)
    
    bug 
    opened by wtfrank 32
  • ManyToManyFields not shown with Django 1.7

    ManyToManyFields not shown with Django 1.7

    I tracked down the cause to utils.Accessor https://github.com/bradleyayers/django-tables2/blob/master/django_tables2/utils.py#L376-L380

                if callable(current):
                    ...
                    current = current()
    

    The problem is, that managers are callable in Django 1.7 and will raise an error when called without arguments. https://github.com/django/django/blob/master/django/db/models/fields/related.py#L654 https://docs.djangoproject.com/en/dev/releases/1.7/#s-using-a-custom-manager-when-traversing-reverse-relations

    I kinda fixed it for me with:

                    if not isinstance(current, BaseManager):
                        current = current()
    

    But I don't know if this is a good solution, since I don't have a very good understanding of the inner workings of tables2 nor django:)

    opened by victor-baumann 22
  • [Bug] sequence in combination with extra_columns does not show extra_columns

    [Bug] sequence in combination with extra_columns does not show extra_columns

    If I have a table

    class MyTable(tables.Table):
        class Meta:
            model=MyModel
            fields=('field1',  'field2')
            sequence=('field1', '...')
    

    a column:

    class Field3Column(tables.Column):
        def __init__(*args, **kwargs):
           someinit
       def render(self,record, table, value, bound_column, **kwargs):
           return somerender()
    
    

    and a view: table = MyTable(extra_columns=('myfield3',Field3Column))

    the table from the view will not contain Field3Column. However, by omitting the sequence on the Meta it does show the Field3.

    bug 
    opened by gabn88 19
  • Documentation should clarify paths used (for templates)

    Documentation should clarify paths used (for templates)

    I found this plugin within days of learning Django and ran into the following problem:

    I did the official Django tutorial the other day and then later installed this plugin via easy_setup. I am not sure if the tutorial's having users edit the template path is what caused this, but when I got to the point where the DT2 guide has you enter "{{ table.as_html }}" in your HTML file, the page returned a "template not found" error until I copied the relevant dirs/files from the DT2 egg into my project's template path.

    I was only able to figure this out b/c Django's official docs list that templates whose path aren't specified are searched for in the Django contrib folder which in my case was extracted from the egg to a folder with the same name:

    "...\Python27\Lib\site-packages\django-1.3.1-py2.7.egg"

    I can see why this happens now, but perhaps a note should be made of this in the docs, as new users may not understand the method behind finding files.

    opened by chenwardT 18
  • Meta options are not inherited.

    Meta options are not inherited.

    Hi,

    I have the following tables:-

        class BaseTable(tables.Table):
            select_column = tables.CheckBoxColumn(verbose_name='', empty_values=('NA',))
    
            class Meta:
                attrs = {'class' : 'cool_table'}
    
        class EditableTable(BaseTable):
            edit_column = EditIconColumn(verbose_name=_('Edit'))
    
            def set_editable(self, flag):
                if flag:
                    self.base_columns['edit_column'].visible = True
                else:
                    self.base_columns['edit_column'].visible = False   
    
        class RoomTable(EditableTable):
            number = tables.Column()
            speciality = tables.Column()
            photo = ImageViewColumn(accessor='room_type.photo')
    

    When I render RoomTable the generated <table> does not have the class attribute. I am able to get that attribute only when I move (or copy) the Meta class from BaseTable to RoomTable.

    Is this a bug or I am using it incorrectly?

    docs 
    opened by applegrew 17
  • tbody attributes (feature request)

    tbody attributes (feature request)

    hello, I'm using jquery-ui to sort tables, to make this work with django_tables2 i need to add an id attribute to the "tbody" tag. I noticed the "tbody" tag is not parameterizable, is it possible to build this feature in?

    I'm looking forward to your answer

    Kind regards, Roel

    opened by roelbouwman 16
  • Instantiate ``BoundColumn``s only once when table is first instantiated

    Instantiate ``BoundColumn``s only once when table is first instantiated

    Hi Bradley,

    This is just a small patch to make sure that BoundColumn objects only get instantiated once. This may help performance when iterating over a large number of rows.

    opened by selwin 15
  • AttributeError: 'GenericForeignKey' object has no attribute 'verbose_name' (django 1.8)

    AttributeError: 'GenericForeignKey' object has no attribute 'verbose_name' (django 1.8)

    Bug #237 was marked as fixed, but there isn't actually any sign of a fix (maybe you forgot to do a git push?). I can't seem to reopen that bug report, so I am reopening a new bug report so that this issue doesn't go unforgotten.

    django release 
    opened by brianmay 14
  • Populate table_data with mixedin ListView's object_list

    Populate table_data with mixedin ListView's object_list

    I'm in the process of moving over to class-based views, in particular the part of our app that used django-tables. Django-tables2 seems a whole lot better, so I picked up v(0.2.0). I'm running django 1.4.0rc1. Once I applied koledennix's handy pull request it looked like the example you give in the docs for class-based view was working, but for the lack of data in the table. The example says this should happen automatically.

    Noticing a comment from a previous pull request:

    The difference between SingleTableView and ListView is that the table view adds a table to the list view. It doesn't force you to populate the table with the same data that the list displays.

    I tried using SingleTableView instead of a SingleTableMixin with Listview in case was understanding the above comment incorrectly. When I checked my context, object_list was full of data, and table_data empty, just as before. Perhaps this is my unfamiliarity with class-based views, but since object_list is only accessible from the template after .as_view creates it, there's no way to pass it in to the MyTableView.as_view() function through table_data = object_list.

    Even if django-tables2 doesn't "force you to populate the table with the same data the list displays", shouldn't you be able to ask it to populate?

    It's also possible this feature isn't missing, but I'm implementing it wrong. Perhaps the example is incorrect? Or is there another bug in 0.2.0 and django1.4 with class-based views I'm not finding? Either way, there's not much in the community about this kind of error, and your class-based documentation is pretty sparse. In which case, I'd re-title this issue to 'Provide Class-Based Documentation', something I'd be happy to contribute to if I could get it working myself.

    opened by christhekeele 14
  • No other context inside the table template

    No other context inside the table template

    I think this comes from this change https://github.com/jieter/django-tables2/issues/547 with the new version 1.21, my forms inside the table template does retreive the csrf token from {% csrf_token %}

    UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.

    {% block table %}
    ...
    <form>
          {% csrf_token %}
    </form>
    ...
    {% endblock table%}
    
    
    opened by Azd325 13
  • Add a get_cell_value method to a BoundRow

    Add a get_cell_value method to a BoundRow

    This will be used to get a rawer version of the rendered value which doesn't have any html.


    I realise this will need some tests before being merged but I thought I'd create the PR to get any feedback on the addition before spending more time on it.

    The need for this arose when I was trying to create a way to get the table data to create an excel download. I had a LinkColumn which had some ' in the content. If using django.utils.html.strip_tags on the get_cell value I was getting the single quotes html escaped to &#39;, now adding this and subclassing the below I can get the raw table data with data formatted/rendered as it was displayed but without any html. Perfect for adding to a csv download!

    class TableWithRawData(tables.Table):
        def raw_data(self):
            heading = [unicode(c.header) for c in self.columns]
            rows = [[r.get_cell_value(column.name) for column in r.table.columns] for r in self.rows]
            return heading, rows
    
    opened by intiocean 13
  • Separate table class definition and instantiation in `MultiTableMixin`

    Separate table class definition and instantiation in `MultiTableMixin`

    This adds a get_tables_classes() method to MultiTableMixin that is called from get_tables() in place of always referring to the tables attribute - this makes it easier to define multiple dynamics custom table table classes in the view - like one can for SingleTableMixin.

    Also added a test to test the new method.

    fixes: #875

    opened by gb119 0
  • Differences between SingleTableMixin and MultiTableMixin?

    Differences between SingleTableMixin and MultiTableMixin?

    I recently switched a view from a single table view to a multi-table view - but I need to generate my table classes dynamically per view. With SingleTableMixin this is easy as one just overrides the get_table_class method, but there isn't an equivalent in MultiTableMixin and I wondered if there was a good reason for this?

    I've hacked out a possible way and will put a pull request in if it's of any interest....

    opened by gb119 0
  • Template engine render multiple times same row

    Template engine render multiple times same row

    Hi guys, I don't know if it's a problem, but I noticed an overload of template renders for each row. The title is always None as you can see and the row counter goes from 0 to 24 (page size is 25) and the same context is repeated each 4 rows (25 * 4 + 3 = 103). Any clues what's going on?

    image

    image

    opened by realnot 1
  • fix: add pagination classes to nav section

    fix: add pagination classes to nav section

    Add pagination classes to nav section When using bootstrap-responsive.html (extends bootstrap.html) the pagination nav section is missing the correct bootstrap classes.

    opened by ikkemaniac 0
  • Why order_FOO doest not have access to request?

    Why order_FOO doest not have access to request?

    Hello!

    I'm trying to order a table by a bookmarked boolean. However, the bookmark data is user-dependent. I can easily show the bookmark in render_bookmark method and use self.request.user in it. However, for the ordering, the request is not yet available.

    The configure method of RequestConfig set the table.request = self.request after the table.order_by = order. Is there a reason for that? Could we safely put the table.request = self.request at the beginning of the method? I think we can but before trying a PR, I would like to check with you.

    Thank you for tables2!

    Ref:

    • PR related to request in table : #705
    • code: https://github.com/jieter/django-tables2/blob/1d0dfa7d9ad209332fb1f6936d213c4363455075/django_tables2/config.py#L33-L69
    opened by weber-s 3
  • How to ensure consistent ordering when sorting?

    How to ensure consistent ordering when sorting?

    When sorting the table by clicking on a header, if there are rows that have the same value, the order can not be consistent from one query to another. Is there a way to specify a "secondary" sorting criteria?

    For example, when user clicks on the price header to sort rows by price, behind the scene I'd like to have ordering = (price, pk) sothat the result is guarantee to be the same, given the same queryset.

    For now, I succeeded with :

    price = tables.Column(order_by=["price", "id"])
    

    However, doing this for every column is tedious, there must be a better way.

    Thanks.

    opened by ddahan 1
Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django.

django-minify-html Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django. Requirements Python 3.8 to 3.10 supported. Django 2.2 to

Adam Johnson 60 Dec 28, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Jan 7, 2023
An app that allows you to add recipes from the dashboard made using DJango, JQuery, JScript and HTMl.

An app that allows you to add recipes from the dashboard. Then visitors filter based on different categories also each ingredient has a unique page with their related recipes.

Pablo Sagredo 1 Jan 31, 2022
Django-shared-app-isolated-databases-example - Django - Shared App & Isolated Databases

Django - Shared App & Isolated Databases An app that demonstrates the implementa

Ajai Danial 5 Jun 27, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
Django-discord-bot - Framework for creating Discord bots using Django

django-discord-bot Framework for creating Discord bots using Django Uses ASGI fo

Jamie Bliss 1 Mar 4, 2022
A Powerful HTML white space remover for Django

HTML Whitespace remover for Django Introduction : A powerful tool to optimize Django rendered templates Why use "django_stip_whitespace" ? Adds line b

null 3 Jan 1, 2022
Fully reponsive Chat Application built with django, javascript, materialUi, bootstrap4, html and css.

Chat app (Full Stack Frameworks with Django Project) Fully reponsive Chat Application built with django, javascript, materialUi, bootstrap4, html and

null 1 Jan 19, 2022
This "I P L Team Project" is developed by Prasanta Kumar Mohanty using Python with Django web framework, HTML & CSS.

I-P-L-Team-Project This "I P L Team Project" is developed by Prasanta Kumar Mohanty using Python with Django web framework, HTML & CSS. Screenshots HO

null 1 Dec 15, 2021
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
APIs for a Chat app. Written with Django Rest framework and Django channels.

ChatAPI APIs for a Chat app. Written with Django Rest framework and Django channels. The documentation for the http end points can be found here This

Victor Aderibigbe 18 Sep 9, 2022
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

Areski Belaid 167 Nov 10, 2022
A Django app to initialize Sentry client for your Django applications

Dj_sentry This Django application intialize Sentry SDK to your Django application. How to install You can install this packaging by using: pip install

Gandi 1 Dec 9, 2021
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is su

Jazzband 1.8k Jan 2, 2023
Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes

Bleach Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes. Bleach can also linkify text safely, appl

Mozilla 2.5k Dec 29, 2022
Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

django-cors-headers A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django a

Adam Johnson 4.8k Jan 3, 2023
A simple app that provides django integration for RQ (Redis Queue)

Django-RQ Django integration with RQ, a Redis based Python queuing library. Django-RQ is a simple app that allows you to configure your queues in djan

RQ 1.6k Jan 6, 2023
A Django app for managing robots.txt files following the robots exclusion protocol

Django Robots This is a basic Django application to manage robots.txt files following the robots exclusion protocol, complementing the Django Sitemap

Jazzband 406 Dec 26, 2022