在DefaultUserCreationForm - django中的模板中显示错误消息

时间:2017-09-26 09:11:17

标签: python django django-forms

我在HTML页面中显示错误消息时遇到问题。我正在使用Django的默认UserCreationForm进行注册页面。它有两个密码字段 - 一个原件和一个用于确认。当用户输入不同的密码时,我收到{/ 3}} / signup /,而我希望错误消息显示在HTML页面中,表示密码不匹配。我已经浏览了文档,并且在代码中添加了一些相关的行,我不知道我哪里出错了。

这是我的views.py:

def adduser(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        print(request.POST)

        if(form.is_valid):
            try:
                user = employees.objects.get(emp_id=request.POST['username'] )
            except employees.DoesNotExist:
                user = None

            print(user)
            if( user != None ):
                if request.POST['username'] in  employees.objects.values_list('manager_id__emp_id',flat=True):
                    g = Group.objects.get(name='Managers')
                    newuser = form.save()
                    newuser.groups.add(g)
                else:
                    g = Group.objects.get(name='Employees')
                    newuser = form.save()
                    newuser.groups.add(g)

                return render(request,'login.html',{'form': form})
            else:
                form = UserCreationForm()
                return render(request,'signup.html', {'form': form, 'msg': 'Enter valid employee id'})
    else:
        form = UserCreationForm()

        return render(request,'signup.html', {'form': form})

这是我的signup.html:

<body>
    <div class="container">
        <div class="page-header">
            <h1>Sign-up Here</h1>      
        </div>
        {% block body %}


        <form method="post">
          {% csrf_token %}
          <font color="orange" size="5px"><p> * Enter your Employee id, as username * </p></font>
          {{ form.as_p }}
          <font  color="red"> {{ msg }} </font><br>
          <font  color="red"> {{ form.password1.errors }} </font><br>
          <font  color="red"> {{ form.password2.errors }} </font><br>

          <br>
          <button class="btn btn-success" type="submit"> Go! </button>
        </form>

        {% endblock %}    

    </div>
</body>

1 个答案:

答案 0 :(得分:1)

问题出在这一行:

if(form.is_valid):

这不是测试表单验证的正确方法, 改为使用:

if form.is_valid():

此外,您不需要多次声明表单,它可以单次完成。 像这样:

def adduser(request):
    form = UserCreationForm(request.POST or None)
    if request.method == 'POST':
        print(request.POST)
        if form.is_valid():
            try:
                user = employees.objects.get(emp_id=request.POST['username'] )
            except employees.DoesNotExist:
                user = None

            print(user)
            if( user != None ):
                if request.POST['username'] in  employees.objects.values_list('manager_id__emp_id',flat=True):
                    g = Group.objects.get(name='Managers')
                    newuser = form.save()
                    newuser.groups.add(g)
                else:
                    g = Group.objects.get(name='Employees')
                    newuser = form.save()
                    newuser.groups.add(g)

                return render(request,'login.html',{'form': form})
            else:
                form = UserCreationForm()
                return render(request,'signup.html', {'form': form, 'msg': 'Enter valid employee id'})
    return render(request,'signup.html', {'form': form})

可能有diffrenmt类型的错误,字段 non_field_errors ,所以请使用这样的方法:

{% 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 %}