Skip to main content

Easy sorting of tables with Django

Project description

webstack-django-sorting

What?

webstack-django-sorting is a Django app which allows for easy sorting of data tables. You don't need to change anything to your views to use it. It provides sorting links for table headers. It is the perfect companion of django-pagination.

There are other powerful projects to sort tables such as django-tables2 but I don't like the high level render_table tag because it requires to define the CSS in Table classes or to write custom templates.

A demonstration of the features is provided in testproj directory.

Features

  • Django or Jinja2 templates
  • Django ORM or Python sorting
  • Switches between ascending, descending, and no sorting
  • Provides links to sort on different criterions
  • Visual feedback on applied ordering
  • Supports 3.6+
  • Supports translation of link titles

To upgrade to webstack-django-sorting v1.0.0+, you must remove the old middleware webstack_django_sorting.middleware.SortingMiddleware from MIDDLEWARE_CLASSES list.

How to use it in your project

The provide is available on PyPI:

pip install webstack_django_sorting

The project provides examples of integration with Django and Jinja2 templates.

For Django templates

  1. Add the application to the INSTALLED_APPS list:

    INSTALLED_APPS = [
        # ...
        'webstack_django_sorting',
    ]
    
  2. Check the request context processor is loaded in TEMPLATES options:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    # ...
                    'django.template.context_processors.request',
                    # ...
                ],
            },
        },
    ]
    
  3. Add this line at the top of your template to load the sorting tags:

    {% load sorting_tags %}
    
  4. Decide on a variable that you would like to sort, and use the autosort tag on that variable before iterating over it:

    {% autosort object_list %}
    

    You can pass the option nulls_first=True (or nulls_first=False) to explicitly define the ordering of NULL (not supported by all databases, Indexing ASC, DESC and NULLS FIRST/LAST)

  5. Now, you want to display different headers with links to sort your objects_list:

    <tr>
        <th>{% anchor first_name _("Name") %}</th>
        <th>{% anchor creation_date _("Creation") %}</th>
    </tr>
    

    The first argument is a field or an attribute of the objects list, and the second one (optional) is a title that would be displayed. The previous snippet will be rendered like this in French:

    <tr>
        <th><a href="/path/to/your/view/?sort=first_name" title="Nom">Nom</a></th>
        <th><a href="/path/to/your/view/?sort=creation_date" title="Création">Création</a></th>
    </tr>
    

    If your application doesn't support internationalization, you can use a simple {% anchor first_name Name %}.

For Jinja2 templates

  1. Define the environment in the TEMPLATES options:

    TEMPLATES = {
        {
            "BACKEND": "django.template.backends.jinja2.Jinja2",
            "DIRS": [],
            "APP_DIRS": True,
            "OPTIONS": {
                "environment": "testproj.testapp.jinja2.env.JinjaEnvironment",
            },
        },
    ]
    
  2. Your environment file should add sorting_anchor and sort_queryset to globals:

    from jinja2.environment import Environment
    from webstack_django_sorting.jinja2_globals import sorting_anchor, sort_queryset
    
    class JinjaEnvironment(Environment):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            self.globals["sorting_anchor"] = sorting_anchor
            self.globals["sort_queryset"] = sort_queryset
    
  3. Now, you can generate header links to sort your queryset.

    <tr>
        <th>{{ sorting_anchor(request, "created_on", "Date") }}</th>
        <!--...-->
    <tr>
    
  4. The queryset should be wrapped with sort_queryset to use the GET request arguments for sorting:

    {% for secret_file in sort_queryset(request, secret_files) %}
    <!--...-->
    {% endfor %}
    

That's it!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

webstack-django-sorting-2.1.1.tar.gz (9.6 kB view details)

Uploaded Source

Built Distribution

webstack_django_sorting-2.1.1-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file webstack-django-sorting-2.1.1.tar.gz.

File metadata

  • Download URL: webstack-django-sorting-2.1.1.tar.gz
  • Upload date:
  • Size: 9.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/33.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.12

File hashes

Hashes for webstack-django-sorting-2.1.1.tar.gz
Algorithm Hash digest
SHA256 48c6e67467a9f27f6bcc6abd92dc68351295e0d2689d398ffb1da778e5bc5bf1
MD5 3a9e867872875d1546647e45b54e5767
BLAKE2b-256 83a48ee1950cd1ca7d361c8a7ad13e6564792d9df828f4bda76fcfc3e04f60f3

See more details on using hashes here.

File details

Details for the file webstack_django_sorting-2.1.1-py3-none-any.whl.

File metadata

  • Download URL: webstack_django_sorting-2.1.1-py3-none-any.whl
  • Upload date:
  • Size: 8.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/33.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.12

File hashes

Hashes for webstack_django_sorting-2.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 cfc1994155b48d24f9cf99f2fc0e55f762ac34564ca02ff93939e005da3f7141
MD5 b24ce0e4c4192fcdf361436d226a7e10
BLAKE2b-256 2e6c0140d1418dadd20eb6bfaa15e04d6cd40582102545bcb43809f75e6f3416

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page