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.