Django:无法使用普通身份验证登录

时间:2016-12-10 21:48:03

标签: python django

我正在使用Django的正常开发服务器,我正在构建一个简单的应用程序。 用户应该能够登录并更改他的电子邮件和密码。 为了更好地理解django系统,我决定自己编写视图,只使用contrib.auth库。 现在来看问题:

一旦用户登录并更改了密码,他就无法再次登录,除非他之前登录标准的django管理页面。

这是我的代码:

views.py

def login(request):
print("test")
if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            return HttpResponseRedirect('/accountManagement/home')
        else:
            form = LoginForm()
    else:
        HttpResponse("form is not valid")
else:
    form = LoginForm()
return render(request, 'accountManagement/login.html', {'form': form})

def home(request):
print(request.user.username)
if request.user.is_authenticated:
    passwordForm = ChangePasswordForm()
    emailForm = ChangeEmailForm()
    return render(request, 'accountManagement/home.html', {'passwordForm': passwordForm, 'emailForm': emailForm})
else:
    return HttpResponseRedirect("/accountManagement/")


def change_password(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        passwordForm = ChangePasswordForm(request.POST)
        if passwordForm.is_valid():
            oldPassword = passwordForm.cleaned_data['oldPassword']
            newPassword = passwordForm.cleaned_data['newPassword']
            newPasswordConfirmation = passwordForm.cleaned_data['newPasswordConfirmation']
            if (newPassword == newPasswordConfirmation) and (request.user.check_password(oldPassword)):
                request.user.set_password(newPassword)
                request.user.save()
                return HttpResponseRedirect("/accountManagement/logout")

            else:
                return HttpResponse("password change failed")
        else:
            return HttpResponse("password form not valid")
    else:
        return HttpResponse("request != POST")
else:
    return HttpResponse("user ist not authenticated")

url.py:

urlpatterns = [
url(r'^$', views.login, name='login'),
url(r'^home', views.home, name='home'),
url(r'^changeEmail', views.change_email, name='changeEmail'),
url(r'^changePassword', views.change_password, name='changePassword'),
url(r'^logout', views.logout_view, name='logout'),
]

表格:

class LoginForm(forms.Form):
    username = forms.CharField(label='Username', max_length=20)
    password = forms.CharField(label='Password', max_length=20)


class ChangeEmailForm(forms.Form):
    newEmail = forms.CharField(label='New Email', max_length=50)


class ChangePasswordForm(forms.Form):
    oldPassword = forms.CharField(label='Old Password', max_length=20)
    newPassword = forms.CharField(label='New Password', max_length=20)
    newPasswordConfirmation = forms.CharField(label='Confirm new Password', max_length=20)

感谢您的帮助,真的无法理解这一点。

1 个答案:

答案 0 :(得分:0)

更改密码会破坏用户身份验证状态,因此您需要再次使用新密码对其进行身份验证:

from django.contrib.auth import login

def change_password(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        passwordForm = ChangePasswordForm(request.POST)
        if passwordForm.is_valid():
            oldPassword = passwordForm.cleaned_data['oldPassword']
            newPassword = passwordForm.cleaned_data['newPassword']
            newPasswordConfirmation = 
                passwordForm.cleaned_data['newPasswordConfirmation']
            if (newPassword == newPasswordConfirmation)\
                    and (request.user.check_password(oldPassword)):
                request.user.set_password(newPassword)
                request.user.save()
                # Re-authentication ===============================
                # =================================================
                user = authenticate(username=request.user.username,
                                    password=NewPassword)
                login(request, user)

                # Why redirect to logout?!
                return HttpResponseRedirect("/accountManagement/logout")

            else:
                return HttpResponse("password change failed")
        else:
            return HttpResponse("password form not valid")
    else:
        return HttpResponse("request != POST")
else:
    return HttpResponse("user ist not authenticated")

另外,我建议您使用CBV(基于类的视图)而不是FBV(基于函数的视图)。

任何情况下,您都可以在视图中使用装饰器@login_required@require_http_methods来移除is_authenticated和方法!=' POST'逻辑。

from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required


@require_http_methods(["POST", ])
@login_required(redirect_field_name='my_redirect_field')
def change_password(request):
    passwordForm = ChangePasswordForm(request.POST)
    if passwordForm.is_valid():
        oldPassword = passwordForm.cleaned_data['oldPassword']
        newPassword = passwordForm.cleaned_data['newPassword']
        newPasswordConfirmation = 
            passwordForm.cleaned_data['newPasswordConfirmation']
        if (newPassword == newPasswordConfirmation)\
                and (request.user.check_password(oldPassword)):
            request.user.set_password(newPassword)
            request.user.save()
            # Re-authentication ===============================
            # =================================================
            user = authenticate(username=request.user.username,
                                password=NewPassword)
            login(request, user)

            # Why redirect to logout?!
            return HttpResponseRedirect("/accountManagement/logout")

        else:
            return HttpResponse("password change failed")
    else:
        return HttpResponse("password form not valid")