Search code examples
djangodjango-viewsdjango-middlewaredjango-sessions

django session object inconsistent behavior


I have custom middleware where i set userdetails for example username as in the following.But each time the user request a new url the the session context is lost and i end up in setting the details again what am i doing wrong here

settings.py

MIDDLEWARE_CLASSES = (
  ....
  ....
  'custom.api.get_username'
)

INSTALLED_APPS = (
  ....   
  'custom',

)

custom/api.py

class get_username(object):
    def process_request(self, request):
       print dir(request.session)
       if request.user.is_authenticated():
           if not in hasattr(request.session,'username'):
              user = api.get_user.(request.user.id).get("result")
              username = user.get('first_name')
              request.session["username"] = u.username
              request.session.save()
              print dir(request.session)

These are two dir print statements below

['TEST_COOKIE_NAME', 'TEST_COOKIE_VALUE', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_new_session_key', '_get_or_create_session_key', '_get_session', '_get_session_key', '_hash', '_session', '_session_cache', '_session_key', 'accessed', 'clear', 'clear_expired', 'create', 'cycle_key', 'decode', 'delete', 'delete_test_cookie', 'encode', 'exists', 'flush', 'get', 'get_expire_at_browser_close', 'get_expiry_age', 'get_expiry_date', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'load', 'modified', 'pop', 'save', 'serializer', 'session_key', 'set_expiry', 'set_test_cookie', 'setdefault', 'test_cookie_worked', 'update', 'values']

['TEST_COOKIE_NAME', 'TEST_COOKIE_VALUE', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_new_session_key', '_get_or_create_session_key', '_get_session', '_get_session_key', '_hash', '_session', '_session_cache', '_session_key', 'accessed', 'clear', 'clear_expired', 'create', 'cycle_key', 'decode', 'delete', 'delete_test_cookie', 'username', 'encode', 'exists', 'flush', 'get', 'get_expire_at_browser_close', 'get_expiry_age', 'get_expiry_date', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'load', 'modified', 'pop', 'save', 'serializer', 'session_key', 'set_expiry', 'set_test_cookie', 'setdefault', 'test_cookie_worked', 'update', 'values']

EDIT:

the firstname is not available and an api call has to be made to get first name and this is the reason i choose this route of using the session variable.Correct me if i am wrong


Solution

  • The right syntax to set data into session is:

    request.session['username'] = u.username
    

    Read django docs for samples:

    def login(request):
        m = Member.objects.get(username=request.POST['username'])
        if m.password == request.POST['password']:
            request.session['member_id'] = m.id
            return HttpResponse("You're logged in.")
        else:
            return HttpResponse("Your username and password didn't match.")
    

    Also check that 'django.contrib.sessions.middleware.SessionMiddleware' is included in your MIDDLEWARE_CLASSES.