django-tables2。 ガイド

オリジナルのドキュメント

ガイド


現在のマニュアルでは、Djangoバージョン1.8.0以降の使用を前提としています。

条件:

モデル-モデル
クエリセット-フェッチ
テンプレート-テンプレート
見る

  1. django-tables2配置しますpip install django-tables2
  2. django_tables2INSTALLED_APPSに追加します
  3. OPTIONSテンプレート設定セクションのcontext_processors「django.template.context_processors.request」を追加します。

小さなアプリケーションを作成することから始めましょう。

まず、モデルについて説明します。

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

いくつかの値を追加して、表示するものを用意します。 Personモデルからテンプレートに選択を転送するためのプレゼンテーションを書いています。

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

テンプレートを書きます:

 {# 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> 

ビューのURLを追加すると、読み込まれたページに次のように表示されます。

画像

選択内容をテンプレートに直接転送する方法では、結果のテーブルをカスタマイズできません。 これを行うには、追加のクラス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'} 

次に、ビューでテーブルのインスタンスを作成し、設定を渡す必要があります。 オブジェクト(オブジェクトのコンテキスト)がテンプレートに送信されます。

 # 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}) 

RequestConfigを使用すると、 request.GETから値を自動的に取得し、テーブルを更新できます。 テーブルをページに分割してソートするときに非常に便利です。

これで、選択をテンプレートに渡す代わりに、オブジェクトを転送できます。

  {% render_table table %} 

現時点では、テーブルの詳細な設定について話すのは時期尚早です。 テーブルを構築するためにデータをテンプレートに転送する方法を決定しました。 次に、設定の適用についてさらに詳しく検討します。

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


All Articles