LoginSignup
7
4

More than 5 years have passed since last update.

django のテンプレートでフィルターを作る

Last updated at Posted at 2015-02-04

前置き

Pythonでmongodbとdjangoを使いながらWebアプリケーションを作っているのですが、テンプレートで繰り返すmongodbから取得したアイテムを特定するためにidを表示したい状況が出てきました。

やり方

{{item._id}}をテンプレートに記載するという方法を考えましたが、item._id"_id": {"$oid": "54cac41fe4b0b3c7e59cff77"}となっているので、そのままでは表示できません。

そこで、テンプレート無いにフィルタを追加することで表示することにしました。

ディレクトリ構成

以下の様なディレクトリ構成にする。templatetagsというディレクトリを作成します。

|-view.py
|-templatetags/
| |- __init__.py
| |- filter.py
|
|-template/
  |- template.html

各ファイルの中身

__init__.pyは、このディレクトリ(templatetags)をパッケージとして認識させるために、お約束で書く必要があるようです。

__init__.py
# 空でOK

filter.pyにフィルタの内容を記載します。ここでは_idの値を文字列にして出力するようにしました。

filter.py
from django import template
register = template.Library()

@register.filter("mongo_id")
def mongo_id(value):
    return str(value['_id'])

template.htmlは以下のようになり、{{オブジェクト|フィルタ}}の形で書けばいいようです。使用するパッケージをロードする必要が有ります。

template.html
{% load filter %}
{% for item in items %}
  <input type="hidden" name="id" value="{{item|mongo_id}}"/>
{% endfor %}

参照

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4