Problem with session in Django after login
Hi am relatively new to Django, been making steady progress with most of the stuff but i have come to be stuck at the sessions part. After i login from my login view, it is successful and redirects to the next link which points to another view. This is where the problem happens, request.user simply returns an empty object and my user not detected as logged in. I tried googling everywhere and reading the official django tutorials but can't come up with anything, can anybody look at my code to see where i did wrong? I also looked at my database and it seems django is correctly storing sessions on my database, could this be something wrong with the cookies?
Below is my 2 simple views.
def mylogin(request):
def errorHandle(error):
form = LoginForm()
return render_to_response('login/login.html', {
'error' : error,
'form' : form,
})
if request.method == 'POST': # If the form has been submitted...
form = LoginForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
username1 = request.POST['username']
password1 = request.POST['password']
u = User.objects.get(username=username1)
user = authenticate(username=username1, password=password1)
if user is not None:
if user.is_active:
# Redirect to a success page.
login(request, user)
username1 = user.last_name + " " + user.first_name 开发者_高级运维
return HttpResponseRedirect("../portal/")
#return render_to_response('login/logged_in.html', {
# 'username': username1,
#},RequestContext(request))
else:
# Return a 'disabled account' error message
error = u'account disabled'
return errorHandle(error)
else:
# Return an 'invalid login' error message.
error = u'invalid login'
return errorHandle(error)
else:
error = u'form is invalid'
return errorHandle(error)
else:
form = LoginForm() # An unbound form
return render_to_response('login/login.html', {
'form': form,
})
def mytest(request):
request.user.username
return render_to_response('login/logged_in.html', {
'username': username1,
})
I think you're reinventing the wheel unnecessarily - all this heavy lifting has already been done. I strongly recommend using django-registration for this, possibly in conjunction with django-profiles. The documentation is a bit abstract but it's extremely well written and very flexible. I never deploy a Django site without it, and never grapple with issues like this one.
精彩评论