Reputation: 1621
I have this form field:
area = forms.DecimalField(max_digits=20)
When I post it I get unicode data:
raise Exception(type(a.get('area',))
the result is
<type 'unicode'>
How can I convert that to float? I want to perform an arithmetic operation on the result.
If I do this:
float(a.get('area', '0'))
Then I get this
float() argument must be a string or a number
Upvotes: 5
Views: 17663
Reputation: 47172
If the form is processed and you get your area
as <type 'unicode'>
then this should suffice to convert it and perform arithmetic on it.
area = form.data['area']
#area should be <type 'unicode'>
area_float = float(area)
Consider the following example
a = u'1.34'
a_float = float(a)
type(a_float)
>> <type 'float'>
However considering that a DecimalField
uses Pythons decimal
type internally and is different from pythons float
which is used by FloatField
.
Decimal Type read more here about the decimal type.
Upvotes: 7
Reputation: 203
you can use this with your variable containing you r data. {variable|Floatformat} I have been using this in the templates . May be that can help .:)
Upvotes: 0
Reputation: 2942
Form submissions are strings (excepted when files are being uploaded, I think.) In Django, the form is automatically converted to the appropriate Python type if the form is valid (how convenient!) You access the data using via cleaned_data
(see Processing the data from the form.)
In this case, you might do something like:
if form.is_valid():
# Form is valid, so do stuff with the form data
# e.g. send email, save to DB etc.
area = form.cleaned_data['area']
# more code here
Upvotes: 0