Login

math filter

Author:
itchyfingrs
Posted:
April 11, 2011
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

A filter for general math operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.template import Node, Library
import math

register = Library()

# taken from http://lybniz2.sourceforge.net/safeeval.html
# make a list of safe functions
math_safe_list = ['acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

# use the list to filter the local namespace
math_safe_dict = dict([(k, getattr(math, k)) for k in math_safe_list])

# add any needed builtins back in.
math_safe_dict['abs'] = abs

@register.filter('math')
def math_(lopr, expr):
    """Evals a math expression and returns it's value.

    "$1" is a placeholder. Insert "$1" in the expression where the value is to be used. All math functions such as abs, sin, cos, floor are supported.
    Example,
        a. You will be redirected in {{ seconds|math:"$1 / 60.0" }} minutes
        b. Square of {{ x }} is {{ x|math:"$1 * $1" }}  
        c. Square root of {{ x }} is {{ x|math:"sqrt($1)" }}
        d. Given x = {{ x }}, (2 + x) * 6 = {{ x|math:"(2 + $1) * 6" }}
    """
    if lopr:
        return eval(expr.replace('$1', str(lopr)), {"__builtins__": None}, math_safe_dict)
    return ''

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.