【问题标题】:only raise validation error after submitting in Django forms仅在 Django 表单中提交后引发验证错误
【发布时间】:2015-11-13 14:08:24
【问题描述】:

创建表单并设置 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)

【问题讨论】:

    标签: python django forms validation


    【解决方案1】:

    问题在于两个请求都是 GET:获取表单的初始请求和提交表单的请求。所以检查if request.method == 'GET'是没有意义的,因为它总是正确的。

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

    if request.GET:
    

    请注意,如果您需要在完全空的提交上显示错误,这将不起作用。

    【讨论】:

    • 如果你知道路,生活有时会如此轻松。谢谢@DanielRoseman
    猜你喜欢
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多