I have a form that asks for a FloatField, and IntegerField.
conc = forms.FloatField(label='Concentration (uM)',required=False)
muxlevel = forms.IntegerField(label='Multiplex level ',required=False)
If a user enters say 0.5, into the muxlevel field, form.is_valid() returns False, and the form is returned saying
"Enter a whole number."
Which is what I expect (it's awesome actually). But if user enters text into either field, say 'asdf', the validation doesn't complain, form.is_valid() returns True, and the value of the form.cleaned_data['muxlevel'] is None. The same thing happens for entering text into the FloatField conc.
That's not what I would have expected, I would rather the user get returned to the form saying "Enter a whole number" or "Enter a floating point value".
I've searched and don't see this problem reported. In fact the documentation says that...
- Normalizes to: A Python float
- Validates that the given value is a float
- Leading and trailing whitespace is allowed, as in Python’s float() function.
EDIT - The view looks like
from .forms import *
def scr_query(request):
summ = ''
if request.method == "POST":
form = QueryForm(request.POST)
if form.is_valid():
if (form.cleaned_data['conc']):
summ += "Concentration < " + str(form.cleaned_data['conc_upper']) + "<br>"
if (form.cleaned_data['muxlevel']):
summ += "Muxlevel > " + str(form.cleaned_data['muxlevel']) + "<br>"
and the form looks like this
class QueryForm(forms.Form):
conc = forms.FloatField(label='Concentration (uM)',required=False)
muxlevel = forms.IntegerField(label='Multiplex level ',required=False)
My reading tells me that python's float() actually gets called to check if the provided string can be coerced into a float. If I do that at the console using float('abc') I get the expected exception. So not sure why It's getting converted to None. Is there some form of text stripping happening before the call to float(), so that it's getting a blank value, and float('') is returning None, as expected?
Any assistance would be greatly appreciated.
Thanks.
QueryForm? Try printing/loggingrequest.POSTto check that the values are present.form = QueryForm({'conc': 'a string', 'muxlevel': 'another string'}); print(form.errors)I get the following errors<ul class="errorlist"><li>muxlevel<ul class="errorlist"><li>Enter a whole number.</li></ul></li><li>conc<ul class="errorlist"><li>Enter a number.</li></ul></li></ul>. Therefore I think that either there's something weird in your form that you haven't shown, orrequest.POSTisn't what you think it is.