Django session not saved

53 views
Skip to first unread message

Malhar Vora

unread,
Oct 5, 2013, 2:42:17 AM10/5/13
to django-d...@googlegroups.com
Hello

I have simple application which checks for username and password in database as well as looks in session for key "user_id". If user exists and login gets successfull then page is redirected to admin page. Here problem is I am storing username in session in one view and retrieving it another but at the time of retrieval it says that the key does not exist in session. 
I have just started learning Django and this is my first project. Please help me.

Here is my views.py : 

====================================================================================================
# Create your views here.
from BaseHTTPServer import BaseHTTPRequestHandler
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from webapp.models import User


def index(request):

    if request.session.get("user_id", False):
        print "Used logged in"
        return HttpResponseRedirect("webadmin")
    else:
        print "Used not logged in"
        return  render_to_response("index.html", {})

@csrf_exempt
def login(request):

    username = request.POST.get("username", None)
    password = request.POST.get("password", None)
    vals = {}
    if not username or not password:
        print "Please enter credentials"
        vals['error'] = "Invalid credentials"
        return HttpResponseRedirect("/")
    elif not isUserExists(username, password):
        print "Invalid credentials"
        vals['error'] = "Invalid credentials"
        return HttpResponseRedirect("/")
    else:
        request.session['user_id'] = username
        request.session.save()
        request.session.modified = True
        print "&&&&&&&&&&&&&&&&& : " + request.session['user_id']
        print "Sessino value written"
        return HttpResponseRedirect("webadmin")

def webadmin(request):
    '''
        Controller to handle /webadmin url
    '''
    return render_to_response("admin.html", {})

def isUserExists(uname, pwd):
    '''
        Check if user exists in database or not
    '''
    users = User.objects.filter(username=uname, password=pwd)
    if len(users) >0:
        print "Access granted"
        return True
    else:
        print "Access denied"
        return False
#########################################################################################

I am using file based session and has following setting in settings.py file.

SESSION_ENGINE = "django.contrib.sessions.backends.file"
SESSION_SAVE_EVERY_REQUEST=True


Thanks

Malhar Vora

Karen Tracey

unread,
Oct 5, 2013, 11:18:39 AM10/5/13
to django-d...@googlegroups.com
Please ask questions about using Django on django-users. The topic of this list is the development of Django itself.
Thanks,
Karen


Reply all
Reply to author
Forward
0 new messages