Search code examples
djangodjango-sessions

Creating Django sessions


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'),
)

Solution

  • 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.