只在Django表单中提交后引发验证错误

时间:2015-11-13 14:08:25

标签: python django forms validation

创建表单并设置required = True后,表单会在加载页面时立即显示验证错误。 当然,这应该只在提交后发生。

如何才能确保在提交后才显示正确的错误?

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)

1 个答案:

答案 0 :(得分:2)

问题是两个请求都是GET:获取表单的初始请求和提交表单的请求。因此,检查if request.method == 'GET'没有意义,因为它始终是真的。

相反,请检查GET字典中是否存在实际信息:

if request.GET:

请注意,如果您需要在完全空提交时显示错误,则无法执行此操作。