views.py
def login_user(request):
if request.POST:
sform = LoginForm(request.POST)
rform = UserForm()
if sform.is_valid():
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username = username,password = password)
if user is not None:
if user.is_active:
login(request,user)
return redirect(request.path)
else:
state = "Your account is not active."
#or first set the user to is active and then log in
return redirect('acitvate_account',user = user)
return render_to_response('home.html',{'state':state,'user':user},context_instance = RequestContext(request))
else:
state = "Incorrect Username or Password"
#sform = LoginForm()
form = LoginForm()
return render_to_response('register.html',{'state':state,'sform':sform,'rform':rform,'form':form},context_instance = RequestContext(request))
else:
state = "Invalid form"
dLoginForm = LoginForm()
rform = PartialSignupForm()
return render_to_response('register.html',{'sform':sform,'rform':rform,'form':form},context_instance = RequestContext(request))
else:
dLoginForm = LoginForm()
rform = PartialSignupForm()
return render_to_response('category.html',{'dLoginForm':dLoginForm,'rform':rform},context_instance = RequestContext(request))
urls.py
urlpatterns += patterns('beenthere.views',
#beenthere urls
(r'^$','index'),
(r'^home2/$','category'),
(r'^accounts/login/$','login_user'),
(r'^accounts/register/$','register_user'),
(r'^home/(?P<user>\w*)$','home'),
(r'^logout/','logout_user'),
)
doubt
how am i suppose to redirect the same url from which request is sent , i tried using request.path but it redirects me to the /accounts/login/ url , which is not desired.
What you need to do is track what the referrer was when you displayed the login form, possibly storing that value in the users session, then redirect the user back to that url once they’ve successfully logged in.
Something along the lines of:
Of course you should also add checks to make sure that the HTTP_REFERER header exists, and make sure the
after_login_urlkey exists (and possibly has a sane value, in case an external site links directly to your log in page, or similar), and have a safe fall back if any of these tests fail (like maybe a user’s profile page, or your sites index page).