我是 Django 新手,我正在尝试创建简单的用户注册/登录应用程序。对于注册,我使用自定义 UserCreationForm:
def registration(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
messages.info(request, "You've successfully registered")
return HttpResponseRedirect('/')
else:
form = UserCreationForm
return render(request, 'accounts/registration.html', {'form': form})
而且效果很好。但是编写登录功能我遇到了困难。我在 /accounts/login 'User' 对象有 AttributeError 没有属性 'backend'。即使登录名/密码正确,authenticate() 似乎也返回 None 对象。
def login(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
userData = form.cleaned_data
user = authenticate(username=userData['username'],password=userData['password'])
auth_login(request, user)
messages.info(request, "You're successfully logged in")
return HttpResponseRedirect('/')
else:
messages.info(request, 'Invalid username or password')
return HttpResponseRedirect('/accounts/login')
else:
form = LoginForm()
return render(request, 'accounts/login.html', {'form': form}
我认为关键是密码以散列形式保存在数据库中,这就是为什么 userData['password'] 与数据库中相同用户名的值不同的原因。
我修复此错误的最佳方法是什么?
跟踪错误
Internal Server Error: /accounts/login
Traceback (most recent call last):
File "C:\Python27\myproject\djcode\first_venv\venv\lib\site-packages\django\core\handlers\base.py"
, line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\myproject\djcode\first_venv\myownproject\accounts\views.py", line 36, in login
auth_login(request, user)
File "C:\Python27\myproject\djcode\first_venv\venv\lib\site-packages\django\contrib\auth\__init__.
py", line 92, in login
request.session[BACKEND_SESSION_KEY] = user.backend
File "C:\Python27\myproject\djcode\first_venv\venv\lib\site-packages\django\utils\functional.py",
line 203, in inner
return func(self._wrapped, *args)
AttributeError: 'User' object has no attribute 'backend'