Question Clarification:
I’m trying to test if the user is authenticated or not for each page request.
I’m trying to use Authentication for the first time in Django and I am not grasping how the login view is supposed to handle authentications.
When I use @login_required, I’m redirecting to “/login” to check if the user is logged in and if not, display the login page. However, trying to redirect back to the original page is causing an infinite loop because it’s sending me back to the login page over and over again.
I’m clearly not grasping how @login_required is supposed to work but I’m not sure what I’m missing. I’ve been searching around for awhile for an example, but everyone uses the default @login_required without the ‘login_url’ parameter.
So for example.. the page I’m trying to access would be…
@login_required(login_url='/login')
def index(request):
And then my login would be.. (obviously incomplete)..
Edit: just to note.. the session variables are set in another view
def login(request):
if '_auth_user_id' in request.session:
# just for testing purposes.. to make sure the id is being set
print "id:",request.session['_auth_user_id']
try:
user = Users.objects.get(id=request.session['_auth_user_id'])
except:
raise Exception("Invalid UserID")
# TODO: Check the backend session key
# this is what I'm having trouble with.. I'm not sure how
# to redirect back to the proper view
return redirect('/')
else:
form = LoginForm()
return render_to_response('login.html',
{'form':form},
context_instance=RequestContext(request)
)
Well, as you say, obviously that’s not going to work, because it’s incomplete. So, until you complete it, you’re going to get an infinite loop – because you haven’t written the code that puts
_auth_user_idinto request.session.But I don’t really know why you’re making that test in the first place. The auth documentation has a perfectly good example of how to write a login view: get the username and password from the form, send them to
authenticateto get the user object, then pass that tologin… done.Edit I think I might see where your confusion is. The
login_requireddecorator itself does the check for whether the user is logged in – that’s exactly what it’s for. There’s no need for you to write any code to do that. Your job is to write the code that actually logs the user in, by callingauthenticateandlogin.