📜 ⬆️ ⬇️

django-tables2. Manual

Original documentation

Manual


The current tutorial assumes the use of Django version 1.8.0 and higher.

Terms:
')
model - model
queryset - selection
template
view - view

  1. We put django-tables2 : pip install django-tables2
  2. Add django_tables2 to INSTALLED_APPS
  3. Add 'django.template.context_processors.request' into context_processors in the OPTIONS template settings section.

Start by creating a small application.

We first describe the model:

# tutorial/models.py class Person(models.Model): name = models.CharField('full name', max_length=50) 

We add several values ​​to show what to show. We write a view to transfer the sample from the Person model to the template.

 # tutorial/views.py from django.shortcuts import render def people(request): return render(request, 'people.html', {'people': Person.objects.all()}) 

Writing a template:

 {# tutorial/templates/people.html #} {% load render_table from django_tables2 %} {% load static %} <!doctype html> <html> <head> <link rel="stylesheet" href="{% static 'django_tables2/themes/paleblue/css/screen.css' %}" /> </head> <body> {% render_table people %} </body> </html> 

Add a url for our view and on the loaded page we see the following:

image

The method of transferring the sample directly to the template does not allow customizing the resulting table. To do this, create an additional class Table :

 # tutorial/tables.py import django_tables2 as tables from .models import Person class PersonTable(tables.Table): class Meta: model = Person # add class="paleblue" to <table> tag attrs = {'class': 'paleblue'} 

Next, you need to create an instance of the table in the view and pass the settings to it. The object (object context) is directed to the template.

 # tutorial/views.py from django.shortcuts import render from django_tables2 import RequestConfig from .models import Person from .tables import PersonTable def people(request): table = PersonTable(Person.objects.all()) RequestConfig(request).configure(table) return render(request, 'people.html', {'table': table}) 

Using RequestConfig allows you to automatically take values ​​from request.GET and update the table. Very useful when paging a table and sorting it.

Now, instead of sending a sample to the template, you can pass an object:

  {% render_table table %} 

At the moment, it's too early to talk about the detailed table setting. We decided on how to transfer data to a template for building tables. Next, consider the use of settings in more detail.

Source: https://habr.com/ru/post/326194/


All Articles