0

I created test project to figure this out.

Here is the form:

class PaymentForm(forms.Form):
  amount = forms.DecimalField(max_digits=2, decimal_places=2, required=False)

Everything works as expected in shell:

>>> from testapp.forms import PaymentForm
>>> f = PaymentForm({'amount': 'a'})
>>> f.errors
{'amount': ['Enter a number.']}
>>> f.is_valid()
False

But if I enter string value in a template and submit the form, it doesn't give any error messages at all and 'it is valid' is being printed.

def add_payment(request):
  if request.method == 'POST':
    payment_form = PaymentForm(request.POST)
    if payment_form.is_valid():
      print('it is valid')
  else:
    payment_form = PaymentForm()
  return render(request, 'testapp/add.html', {'payment_form': payment_form})

When i make the field required, the form gives the expected 'Enter a number' and the view - 'Required field' error message.

Any ideas how to make it work? Is this how django forms supposed to work? Because i couldn't find anything by googling.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
Negotiare
  • 31
  • 2
  • does it prints **it is valid** ?? – rahul.m Mar 24 '21 at 11:39
  • 1
    Exaclty what does `print(request.POST)` print? – Willem Van Onsem Mar 24 '21 at 11:41
  • "It is valid" is printed. print(request.POST) gives blank value for amount: – Negotiare Mar 24 '21 at 12:07
  • 1
    Form is valid because amount got nothing. 'amount': [''] in Form amount is required=False Put some value when you submit the form then show print(request.POST) – Shaid Hasan Shawon Mar 24 '21 at 12:24
  • The question wasn't actually django related, but had to do with HTML. That's why I wasn't able to find similar questions here on stackoverflow. As I found out on [this thread](https://stackoverflow.com/questions/18852244/how-to-get-the-raw-value-an-input-type-number-field), "the browser is supposed to set the value to an empty string if the input isn't a valid floating point number." – Negotiare Mar 24 '21 at 13:45

0 Answers0