【问题标题】:Django Forms: Cannot show Validation ErrorDjango 表单:无法显示验证错误
【发布时间】:2019-01-30 13:22:04
【问题描述】:

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

验证工作正常,如果密码匹配,则输入并存储值,如果不匹配,则没有任何反应。

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

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

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 语句中缺少某些内容。

感谢您的任何建议。

【问题讨论】:

    标签: python django


    【解决方案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})
    

    【讨论】:

      猜你喜欢
      • 2013-12-08
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 2016-07-12
      • 2012-04-05
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多