Specifically, after authentication and redirect, request.user is an anonymous user.
login (view function)
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
#django.contrib.auth.login
Login(request, form.get_user())
str = reverse('cm_base.views.index')
return HttpResponseRedirect(str)
else:
# Their password / email combination must have been incorrect
pass
else:
form = LoginForm()
return render_to_response('cm_base/login.html',
{"DEBUG": True,
'form' : form
},
context_instance=RequestContext(request))
in the index view, I removed the login_required decorator and tested the request.user object
def index(request):
test = request.user.is_authenticated()
return render_to_response('cm_base/index.html',
{"DEBUG": True,
"user": request.user,},
context_instance=RequestContext(request))
Test returns false.
Fix
I ended up just calling the index view directly. I am still confused as to why the user object was lost when I called HttpResponseRedirect.
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST) # Not shown in this example
if form.is_valid():
Login(request, form.get_user())
str = reverse('cm_base.views.index')
return index(request)
else:
# Their password / email combination must have been incorrect
pass
else:
form = LoginForm()
A lot of things going on here that shouldn't be. First, you don't need to pass request.user
, its available by default as long as you are using RequestContext
, which you are.
Login()
this method, what exactly is it doing? Django provides a built-in login
method that you should be using if you are using the default authentication backend.
You are also not checking if a user is enabled or disabled.
Here is a different version of your code, adapted from the example in the documentation:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
def login_view(request):
form = LoginForm(request.POST or {})
ctx = {'form': form}
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username, password)
if not user:
ctx['errors'] = 'Invalid Login'
return render(request, 'login.html', ctx)
if not user.is_active:
ctx['errors'] = 'User is locked'
return render(request, 'login.html', ctx)
login(request, user)
return redirect('home')
else:
return render(request, 'login.html', ctx)
What auth backend are you using? If it is something other than the ModelBackend make sure your get_user method is correct. It sounds as if the auth middleware is sending a different identifier (like the pk instead of a username) than the one you are looking for in your get_user method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With