FloatField with safe expression parsing

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from __future__ import division
from django import forms
from math import *

safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
        'de grees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
        'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
        'sqrt', 'tan', 'tanh'] 

safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ]) 
safe_dict['abs'] = abs 

class MathFloatField(forms.FloatField):
    "FloatField which allows math expressions"

    def clean(self, value):
        try:
            return float(eval(value, {"__builtins__":None}, safe_dict))
        except:
            raise forms.ValidationError("Enter a number or math expression")

More like this

  1. {% eval %} templatetag-evaluate expressions by diverman 3 years, 5 months ago
  2. math tag by itchyfingrs 2 years ago
  3. RPN template math by durka 4 years, 6 months ago
  4. Significant digits filter by joelegner 4 years, 2 months ago
  5. Slugify alternative by exogen 6 years, 1 month ago

Comments

(Forgotten your password?)