その中の TemplateView は与えられたテンプレートをレンダリングする際に使用する。
TemplateView を利用する場合、レンダリングするためのデータ取得は get_context_data をオーバライドし、辞書型のコンテキストを返せばよい。
def get_context_data(self, **kargs):
# データ取得するための処理...
return {取得したデータは辞書型で返す}
以下の例では、取得したデータを django-tables2 を利用して表示している。
[view.py]
class ActorTemplate(TemplateView):
template_name = "sample.html"
def get_context_data(self, **kargs):
actors = Actor.objects.order_by("first_name", "last_name")
actortable = ActorTable(actors)
RequestConfig(self.request,
paginate={"per_page": 20}).configure(actortable)
return {"title": "HOGE TITLE",
"actortable": actortable}
[models.py]
class Actor(models.Model):
actor_id = models.SmallIntegerField(primary_key=True)
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
last_update = models.DateTimeField()
[tables.py]
class ActorTable(tables.Table):
first_name = tables.Column(accessor="first_name",
verbose_name="First Name",
orderable=False,
attrs={"th": {"id": "first_name_id"}}
)
last_name = tables.Column(accessor="last_name",
verbose_name="Last Name",
orderable=False,
attrs={"th": {"id": "last_name_id"}}
)
[urls.py]
urlpatterns = [
url(r'^actors/',
ActorTemplate.as_view()),
]
[sample.html]
{% load render_table from django_tables2 %}
{% load static %}
<html>
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href="{% static 'django_tables2/themes/paleblue/css/screen.css' %}" />
<style type="text/css">
th#first_name_id {width: 150px}
th#last_name_id {width: 150px}
</style>
</head>
<body>
{% render_table actortable %}
</body>
</html>
0 件のコメント:
コメントを投稿