UserCreationForm,哈希密码和authenticate()

时间:2013-07-05 10:36:34

标签: django authentication login hash registration

我是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上有AttributeError'用户'对象没有属性'后端'。即使登录/密码正确,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']与db中相同用户名的值不一致。

我最好的方法是修复这个错误吗?

跟踪错误

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'

1 个答案:

答案 0 :(得分:0)

在您的代码中尝试此操作

user = authenticate(username=userData['username'],password=userData['password'])
if user:
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    auth_login(request, user)
else:
    print "invalid login"