Reputation: 17372
I am facing a problem while building a Django web app. I want that if a user logs into his account, his session should be stored and when he agains visits the login page ,he should be redirected to his home page. I have tried using
Here is my code.
Views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
def index(request):
return HttpResponse("Index Page")
@login_required
def home(request):
ctx = {}
return render_to_response('auth/home.html',ctx, context_instance = RequestContext(request))
Urls.py
from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout
urlpatterns = patterns('',
url(r'^$','apps.auth.views.index'),
)
urlpatterns = patterns('',
url(r'cc/', login, kwargs = {'template_name' : 'auth/cc.html'} , name = 'cc_login'),
url(r'logout/', logout, name = 'cc_logout'),
url(r'home/','apps.auth.views.home', name = 'cc_home'),
)
Upvotes: 0
Views: 133
Reputation: 36
I ran into the same situation with my django project.
I solved it by making a view that was similar too:
def login_page(request):
if request.user.is_authenticated():
return redirect(<insert your desired page here>)
else:
return render(<whatever the login page is>)
This way, if the user is logged in, they will be redirected to whatever page you want them to be.
EDIT:
In response to the comments below, I am modifying my answer (original is still above). Here is what I have done to solve your problem.
from django.contrib.auth.views import login
def custom_login(request, **kwargs):
"""
Redirects the user to the desired page if they are authenticated
"""
if request.user.is_authenticated():
return redirect(<whatever page or view you want them to go to>)
else:
return login(request, **kwargs)
For example, your kwargs could be {'template_name': 'your_login_template.html', 'authentication_form': YourCustomRegistrationFormClass}
If you're using the standard login and registration procedures, just leave the kwargs part blank.
Upvotes: 2
Reputation: 403
I'm fairly new to Django, but have you tried overriding the default login view?
views.py
from django.contrib.auth import views as auth_views
from django.shortcuts import redirect
def login(request, *args, **kwargs):
if request.method == 'POST':
request.session.set_expiry(0) # Remember user session
if request.user.is_authenticated():
return redirect(USER_PAGE_ADDRESS)
return auth_views.login(request, *args, **kwargs)
urls.py
urlpatterns = patterns('',
url(r'cc/', APP_NAME.views.login, kwargs = {'template_name' : 'auth/cc.html'} , name = 'cc_login'),
...
)
Upvotes: 0