我有以下功能来更改密码并显示用户个人资料,但在提交表单而不是重定向到'profile/'
页面时,我收到错误The view core.views.change_password didn't return an HttpResponse object. It returned None instead.
,这是为什么?
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
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) #this function keeps the user logged in afte they change their password
# request.user could not have been passed in because that would pass in 'AnonymousUser', however
#form.user gets the user who was filling in the form and passes it to the function
return redirect('/profile')
else:
form = PasswordChangeForm(user = request.user)
args = {'form': form} # gives access to the form in the template
return render(request, 'core/change_password.html', args)
def view_profile(request):
args = {'user': request.user} #
return render(request, 'core/profile.html', args)
注意:个人资料页面适用于网站的其他部分,例如登录后,用户被重定向到他们的个人资料页面,没有任何问题。
答案 0 :(得分:0)
您应该将最后两行移出else
块。这样,当表单无效时,您将返回POST请求的响应。
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(data= request.POST, user = request.user)
if form.is_valid():
...
return redirect('/profile')
else:
form = PasswordChangeForm(user = request.user)
args = {'form': form} # gives access to the form in the template
return render(request, 'core/change_password.html', args)