LoginSignup
5
1

More than 3 years have passed since last update.

Djangoのtemplateで演算処理を行う方法

Last updated at Posted at 2020-11-15

はじめに

django-mathfiltersというモジュールを利用することでテンプレート上での演算処理ができるようになります。この記事では、その実装方法について紹介します。

参考

django-mathfilters · PyPI

環境

Python(3.6.2)
Django(2.1.7)

インストール方法

django-mathfiltersをインストール

pip install django-mathfilters

mathfiltersをINSTALLED_APPSに追加

settings.py
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sass_processor',
    'storages',
    'mathfilters', # ← 追加
]

テンプレートから読み込む

- load mathfilters

これでテンプレート上で演算処理が可能になります。

演算方法

  • sub – 減算
  • addition – 加算
  • mul – 乗算
  • div – 除算
  • intdiv – 整数除算
  • abs – 絶対値
  • mod – 剰余
template_file.html.haml
- load mathfilters

%ul
  %li
    10 - 2 = {{ 10 | sub:2 }}  # 8
  %li
    10 + 5 = {{ 10 | addition:5 }} # 15
  %li
    10 × 3 = {{ 10 | mul:3 }} # 30
  %li
    10 ÷ 2 = {{ 10 | div:2 }} # 5
  %li
    | -10 | = {{ -10 | abs }} # 10
  %li
    20 ÷ 3 = {{ 20 | mod:3 }} # 2
5
1
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
5
1