Reputation: 119
I am new to Django and i'm trying create simple user registration/login app. For registration I'm using custom 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})
And it works well. But writing login function I faced with difficulties. I've got AttributeError at /accounts/login 'User' object has no attribute 'backend'. It seems that authenticate() returns None object even when login/password correct.
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}
I think the point is that password saved in DB in hashed form and that's why userData['password'] not identical to value in db for the same username.
What i the best way to fix this bug?
Trace error
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'
Upvotes: 0
Views: 1554
Reputation: 422
try this in your code
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"
Upvotes: 0