我是新來的Django,我想創建簡單的用戶註冊/登錄應用程序。 對於註冊我使用自定義的UserCreationForm: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處有AttributeError'User'對象沒有'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}
我認爲這一點是密碼散列形式保存在數據庫,這就是爲什麼用戶數據[「密碼」]不等同於分貝爲相同的用戶名值。
我最好的方法來解決這個錯誤?
跟蹤誤差
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'
拜託你給UserCreationForm代碼,可能是保存密碼直接進入數據庫。如果你的user.set_password(<密碼值>),那麼它將Django的密碼值進行編碼,然後在驗證時它會正確檢查它。 –
和跟蹤錯誤 – lalo
我使用默認的UserCreationForm http://docs.nullpobug.com/django/trunk/django.contrib.auth.forms.UserCreationForm-class.html,不要改變它,所以在forms.py我只有LoginForm(用戶名/密碼)。可能是我應該以某種方式糾正它? 添加跟蹤錯誤 – Leval