首页 > 解决方案 > 如果 Django form_template 中的密码和用户名不正确,则显示错误消息

问题描述

当用户使用form_template. 到目前为止,我尝试了以下方法,但它不起作用。

表格.py:

class UserForm(forms.Form):
    username=forms.CharField(max_length=50)
    password=forms.CharField(widget=forms.PasswordInput)

    model=User
    fields=['username', 'password']

视图.py:

class loginform(View):

    template_name='essay/Login.html'
    form_class=UserForm

    def get(self,request):     # if the request is get then only view the function
        form=self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self,request):
        form=self.form_class(request.POST)
        if form.is_valid():
            #user = form.save(commit=False)  # it doesnot save in database, it is used to et clean the values
            # clean data
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            # authenticate user:
            user = authenticate(username=username, password=password)

            if user is not None:
                login(request, user)
                if(request.user.is_prof==True):
                    return redirect('essay:file', )
                else:
                    return redirect('essay:stdprofile')
            else:
                return render(request,self.template_name, {
                    'error_message': ' Login Failed! Enter the username and password correctly', })
        else:
            msg = 'Errors: %s' % form.errors.as_text()
            return HttpResponse(msg, status=400)

        return render(request, self.template_name, {'form': form})

表单模板:

{% for field in form %}
 <div class="form-group">
  <label class="control-label col-sm-2">{{ field.label_tag }}</label> 
  <div class="col-sm-10">{{ field }}</div>   <!-- inputs on the rigth -->
 </div>
{% endfor %}  

登录.html:

<body>
    <div class="login-card">
      <h1>Log-in</h1><br>
      <form class="form-horizontal" action="" method="POST" enctype="multiport/form-data">
          {% csrf_token %}
          {% include 'essay/form_template.html' %}
          <input type="submit" name="login" class="login login-submit" value="login">
      </form>
      {% error_message %}
    </div>

</body>

我输入无效凭据时遇到的问题,用户名和密码字段消失了,它也没有显示错误消息。

标签: pythondjangodjango-forms

解决方案


在表单页面的字段中添加,

{{field.errors}}

或在 csrf 标签下添加,

{{form.errors}}

这将显示您所有的字段错误,对于非字段错误添加,

{{form.non_field_errors}}

此外,您还可以使用 Django 内置消息来显示您的自定义消息。


推荐阅读