my HTML form is
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">
<strong>{{message}}</strong>
</div>
{% endfor %}
{% endif %}
{% if form.errors %}
{% for field in form %}
{% for error in field.error %}
<div class="alert alert-danger" role="alert">
<strong>{{error|escape}}</strong>
</div>
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger" role="alert">
<strong>{{error|escape}}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
我views.py当我输入错误的密码时,它将我重定向到同一页面,如果我不返回is_valid
的其他部分,它会给我对象返回错误。我该怎么做显示表单错误在前端
def change_password(request):
if request.user.is_authenticated:
if request.method == "POST":
form = PasswordChangeForm(request.user , request.POST)
if form.is_valid():
user = form.save
update_session_auth_hash(request , user)
messages.success(request , "Your password is successfully changed")
return redirect('index')
else:
messages.error(request , "Please correct the error below.")
return redirect('change_password')
else:
form = PasswordChangeForm(request.user)
return render(request , "change-password.html" , {'form':form})
else:
messages.error(request , "Please login to see that page")
return redirect('login')
看起来你在这行末尾缺少了's',{% for error in field.error %}
应该在你的模板中是...in field.errors %}
。
views.py中将redirect(view_name)
替换为:
HttpResponseRedirect(reverse('app_name:view_name'))
def change_password(request):
if request.user.is_authenticated:
if request.method == "POST":
form = PasswordChangeForm(request.user , request.POST)
if form.is_valid():
user = form.save
update_session_auth_hash(request , user)
messages.success(request , "Your password is successfully changed")
return HttpResponseRedirect(reverse('app_name:index'))
else:
messages.error(request , "Please correct the error below.")
return HttpResponseRedirect(reverse('app_name:change_password'))
else:
form = PasswordChangeForm(request.user)
return render(request , "app_name/change-password.html" , {'form':form})
else:
messages.error(request , "Please login to see that page")
return HttpResponseRedirect(reverse('app_name:login'))
你也可以用基于类的视图来代替这个函数:
#if user is not logged in
#then will be redirected to the login page defined in settings.py
@method_decorator(login_required, name='dispatch')
class YourViewName(PasswordChangeView):
template_name = 'app_name/change-password.html'
form_class = PasswordChangeForm #You can use custom form here
success_url = reverse_lazy('app_name:index')
#add these functions only if you want to add these messages
#to default Django messages
def form_valid(self, form):
messages.success(self.request , "Your password is successfully changed")
return super().form_valid(form)
def form_invalid(self, form):
messages.error(self.request , "Please correct the error below.")
return super().form_invalid(form)