Django表单:无法显示验证错误

时间:2018-08-24 05:36:50

标签: python django

我有一个Django表单,仅当他的密码与我设置的预定义密码匹配时,我才允许用户提交值Pass_matcher

验证工作正常,例如,如果密码匹配,则输入并存储值,否则,什么也不会发生。

但是,如果密码不匹配,我希望显示一条简单的自定义警告消息。我看了诸如herehere之类的其他SO问题,但似乎无法正确解决。

注意:如果用户输入正确的密码,我不想重定向到另一个页面。

forms.py

from django import forms

class TactForm(forms.Form):

        password = forms.CharField(widget=forms.PasswordInput(
                attrs = {
                        'class' : 'form-control mb-2 mr-sm-2 mb-sm-0',
                        'placeholder' : 'Enter Password:',
                        'id' : 'inlineFormInput',
                        'required' : 'true'
                }
        ), required = True, label='Tact Password', max_length=100)


        tacttime = forms.CharField(widget=forms.TextInput(
                attrs = {
                        'class': 'form-control mb-2 mr-sm-2 mb-sm-0',
                        'placeholder': 'Enter Tact Time:',
                        'id' : 'inlineFormInput2'
                }
        ),label='Tact Time', max_length=100)

        def clean(self):
                cleaned_data = super(TactForm,self).clean()
                password = cleaned_data.get('password')
                current_tact = cleaned_data.get('tacttime')

                if password != 'Pass_matcher':
                        print('incorrect') #this prints to console if incorrect
                        raise forms.ValidationError('Incorrect Password') # this does not work

                else:
                        print('correct') #this prints to console if correct
                        return cleaned_data

views.py

def details(request):

    form = TactForm(request.POST or None)
    if request.method == 'POST':
            form = TactForm(request.POST)
            if form.is_valid():
                    print('here1')
                    current_tact = form.cleaned_data['tacttime']
                    password = form.cleaned_data['password']

            else:
                    form = TactForm()

   return render(request, 'linedetails/index.html',{'form':form})

模板

<div class="user_in" style="text-align:center;">
                <form class="form-inline" method="POST" action="{% u$
                        {% csrf_token  %}
                        {{ form.password }}
                        {{ form.tacttime }}
                        <br>
                        <button type="submit" class="btn btn-outline>
                </form>
</div>

下面的代码是实验性的

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

我不明白为什么如果raise forms.ValidationError('Incorrect Password') 上面的语句正确打印到终端上,却没有显示。

我认为views.py脚本的else语句中缺少某些内容。

谢谢您的建议。

1 个答案:

答案 0 :(得分:1)

如果表单无效,则重新定义了表单实例。只需删除else块即可修复它:

def details(request):

    form = TactForm(request.POST or None)
    if request.method == 'POST':
            form = TactForm(request.POST)
            if form.is_valid():
                    print('here1')
                    current_tact = form.cleaned_data['tacttime']
                    password = form.cleaned_data['password']

   return render(request, 'linedetails/index.html',{'form':form})

您实际上也不需要if request.method == 'POST'验证,因为表单将自动在此处form = TactForm(request.POST or None)填充邮政数据。因此,您只需将视图重写为此:

def details(request):
    form = TactForm(request.POST or None)
    if form.is_valid():
        print('here1')
        current_tact = form.cleaned_data['tacttime']
        password = form.cleaned_data['password']

    return render(request, 'linedetails/index.html',{'form':form})