- Author:
- joelegner
- Posted:
- March 15, 2010
- Language:
- Python
- Version:
- 1.1
- Tags:
- fields forms parser math eval parsing floatfield
- Score:
- 0 (after 0 ratings)

This FloatField replacement allows users to enter math expressions, such as:

4/5 + sqrt(32)

And will evaluate them safely when the field's clean() function is called. In the example above, it will evaluate to a float value of about 6.457.

Reference:

http://lybniz2.sourceforge.net/safeeval.html

The available functions are listed herein. Note that the from **future** import division causes integer division expressions to be evaluated as floats. For example "1/2" evaluates as 0.5 when it would otherwise have evaluated to 0 (assuming Python 2.X).

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

- math tag by itchyfingrs 3 years, 11 months ago
- RPN template math by durka 6 years, 5 months ago
- {% eval %} templatetag-evaluate expressions by diverman 5 years, 4 months ago
- Currency Fields with newforms by sago 7 years, 11 months ago
- Tamper safe HiddenFields by alexmeisel 6 years, 4 months ago

## Comments

Please login first before commenting.