После создания формы и установки required = True форма показывает ошибки проверки сразу при загрузке страницы. Конечно, это должно произойти только после отправки.только повышать ошибку проверки после отправки в формах Django
Как я могу убедиться, что правильные ошибки отображаются только после отправки?
forms.py
class CurrencyConverterForm(forms.Form):
base_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), required=True)
counter_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), required=True)
base_amount = forms.FloatField(required=True)
index.html
<form action="" method="get">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.base_currency.errors }}
<label for="{{ form.base_currency.id_for_label }}">From Currency</label>
{{ form.base_currency }}
</div>
<div class="fieldWrapper">
{{ form.counter_currency.errors }}
<label for="{{ form.counter_currency.id_for_label }}">To Currency</label>
{{ form.counter_currency }}
</div>
<div class="fieldWrapper">
{{ form.base_amount.errors }}
<label for="{{ form.base_amount.id_for_label }}">Amount</label>
{{ form.base_amount }}
</div>
</form>
views.py
def index(request):
counter_amount = ""
if request.method == 'GET':
form = CurrencyConverterForm(request.GET)
if form.is_valid():
# Get the input data from the form
base_currency = form.cleaned_data['base_currency']
counter_currency = form.cleaned_data['counter_currency']
base_amount = form.cleaned_data['base_amount']
# Calculate the counter_amount
counter_amount = get_conversion_amount(base_currency, counter_currency, datetime.now(), base_amount)
# Retrieve the counter amount from the dict
counter_amount = counter_amount['GetConversionAmountResult']
# Maximize the number of decimals to 4
if counter_amount.as_tuple().exponent < -4:
counter_amount = "%.4f" % counter_amount
else:
form = CurrencyConverterForm()
context = {
'form': form,
'counter_amount': counter_amount
}
return render(request, '../templates/client/index.html', context)
Жизнь может быть такой легкой, если вы знаете дорогу. Благодаря @DanielRoseman –