Reputation: 35
I'm struggling to show error message in change_password in Django.
I tried all the ways I know to show errors in the template file, but nothing shows up when I put some wrong information on purpose. I thought it's because of redirecting when the form is not valid. But, the changing password feature doesn't work without the redirecting.
Can anyone suggest a way to do that?
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 template
<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>
Upvotes: 2
Views: 138
Reputation: 16505
Try without redirecting when there is an error, like this:
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)
As you can see, like this the line return render(...
is also called when the form is not valid.
Upvotes: 1