如何在Django中的change_password中显示错误消息

时间:2018-05-31 19:34:23

标签: django

我正在努力在Django的change_password中显示错误消息。

我尝试了所有我知道的方式来显示模板文件中的错误,但是当我故意提供一些错误的信息时,没有任何显示。 我认为这是因为当表单无效时重定向。但是,更改密码功能在没有重定向的情况下无法正常工作。

有人可以建议一种方法吗?

views.py

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST, user=request.user)

        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            return redirect('/accounts/profile')
        else:
            return redirect('/accounts/change-password')

    else:
        form = PasswordChangeForm(user=request.user)

        args = {'form': form}
        return render(request, 'accounts/change_password.html', args)

HTML模板

<form method="POST">
    {% csrf_token %}
    <p class="error-message">
        {{ form.errors.old_password }}
        {{ form.errors.new_password1 }}
        {{ form.errors.new_password2 }}
        {{ form.non_field_errors }}
        {% if form.non_field_errors %}
            {% for error in form.non_field_errors %}
                {{ error }}
            {% endfor %}
        {% endif %}
    </p>
    <div class="form-group row">
        <label for="inputPassword" class="col-sm-3 col-form-label">Old Password</label>
        <div class="col-sm-9">
            <input type="password" class="form-control" name="old_password" placeholder="Old Password" required autofocus>
        </div>
    </div>
    <div class="form-group row">
        <label for="inputPassword" class="col-sm-3 col-form-label">New Password</label>
        <div class="col-sm-9">
            <input type="password" class="form-control" name="new_password1" placeholder="New Password" required>
        </div>
    </div>
    <div class="form-group row">
        <label for="inputPassword" class="col-sm-3 col-form-label">Confirm New Password</label>
        <div class="col-sm-9">
            <input type="password" class="form-control" name="new_password2" id="inputPassword" placeholder="Confirm New Password" required>
        </div>
    </div>

    <input class="btn btn-modvisor btn-block" type="submit" name="" value="Submit">
</form>

1 个答案:

答案 0 :(得分:1)

在出现错误时尝试不重定向,如下所示:

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST, user=request.user)

        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            return redirect('/accounts/profile')
    else:
        form = PasswordChangeForm(user=request.user)

    args = {'form': form}
    return render(request, 'accounts/change_password.html', args)

正如您所看到的那样,当表单无效时,也会调用行return render(...