Django не выдает ошибку формы на стороне клиента, если форма недействительна
Итак, у меня есть следующая модель и модельформа, которые обрабатываются представлением. Теперь, если пользователь вводит число > 99.99 в поле ввода числа, валидация формы не проходит из-за заданных параметров поля monthly_amount
, что нормально. Однако на фронтенде не отображается ошибка.
class Benefit(models.Model):
company = models.ForeignKey('company.Company', on_delete=models.CASCADE)
monthly_amount = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
...
def __str__(self):
return f'ompany {self.company.name}'
class BenefitForm(ModelForm):
class Meta:
model = Benefit
exclude = ('company', )
...
monthly_amount = forms.DecimalField(label='Monthly $ equivalent', widget=forms.NumberInput(attrs={'class': benefit_tailwind_class}))
А это представление y, обрабатывающее форму
def render_dashboard_benefits(request):
# Get a qs of available Benefits the company of the authenticated user offers
current_user = request.user
qs_benefits = Benefit.objects.filter(company__userprofile=current_user).order_by('-created_at')
ctx = {
'page': 'Benefits',
'qs_benefits': qs_benefits,
}
# Create a blank form instance on GET requests and add it to the context
if request.method == 'GET':
form = BenefitForm()
ctx['form'] = form
else:
# Create clean form
form = BenefitForm()
ctx['form'] = form
# Create new Benefit instance on POST request
new_benefit = BenefitForm(request.POST)
if new_benefit.is_valid():
# If the instance is valid create it but dont save it yet
new_benefit_instance = new_benefit.save(commit=False)
# Get the related company instance and assign it to the model instance
new_benefit_instance.company = current_user.company
# Finally save the instance
new_benefit_instance.save()
return render(request, 'dashboard/dashboard_benefits.html', ctx)
else:
# Return failed form instance to display error
print(new_benefit.errors)
ctx['form'] = new_benefit
return render(request, 'dashboard/dashboard_benefits.html', ctx)
return render(request, 'dashboard/dashboard_benefits.html', ctx)
# template
..
{{ form.non_field_errors }}
..
Когда я печатаю ошибки неработающего экземпляра формы, я получаю
<ul class="errorlist"><li>monthly_amount<ul class="errorlist"><li>Ensure that there are no more than 2 digits before the decimal point.</li></ul></li></ul>
Но как показать это пользователю?