我正在尝试使用 Django,并尝试创建一个登录/注册应用程序。这就是我卡住的地方——我可以注册用户,但是我不能用他们登录。这是我认为相关的代码:
视图.py
def login(request, template='accounts/sign_in.html'):
if request.user.is_authenticated():
return redirect(reverse('games'))
if request.method == 'POST':
post = request.POST.copy()
if 'password' in post:
post['password'] = make_password(post['password'])
form = AuthenticationForm(data=post)
if form.is_valid():
login(request, form.get_user())
messages.success(
request, "Successfully logged in.", extra_tags='success')
return redirect(reverse('games'))
else:
messages.warning(
request, "Wrong username or password." + request.POST['username'] + " " + request.POST['password'], extra_tags='error')
return redirect(reverse('login'))
return views.login(request, template)
def register(request, template='accounts/sign_up.html'):
if request.user.is_authenticated():
return redirect(reverse('home'))
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
new_user = User(
username=form.cleaned_data['username'],
password=make_password(form.cleaned_data['password1']),
is_active=True,
)
new_user.save()
messages.success(request, "Your account was successfully created.")
return redirect(reverse('games'))
else:
form = RegisterForm()
return render(request, template, {'register_form': form})
当我尝试使用我创建的用户(用户名:qwe,密码:qweqweqwe)登录时,我会重新登录以再次登录,但消息中会打印完全相同的用户名和密码:
Wrong username or password.qwe qweqweqwe
但是,当我尝试交互式 shell 时,我得到了以下结果:
>>> User.objects.all()
[<User: admin>, <User: asd>, <User: qwe>]
>>> User.objects.all()[2]
<User: qwe>
>>> User.objects.all()[2].password
u'pbkdf2_sha256$10000$HM2k6uDntJ68$DLqHKcGxtJG7pJC7tbZcm29vB88LEgaw2xroqZEkTFw='
所以我有这样一个用户,它是一个有效的帐户。