0

Hi i am trying to set a value in session but not getting the value, I don't know what I am doing wrong.

Setting Value

class ClView(GenericAPIView):

    def get(self, request, *args, **kwargs):
        # Get Method Code
    def post(self, request, *args, **kwargs):
        cid = request.data['id'] 
        self.request.session['myid'] = cid
        request.session.modified = True
        return Response(status=status.HTTP_202_ACCEPTED)

Getting Value

class MainView(APIView):
    def get(self, request, *args, **kwargs):
        cid = self.request.session.get('myid')
        return Response({"id":cid})

'django.contrib.sessions.middleware.SessionMiddleware', in the middlewares and already tried without 'self'

dev
  • 109
  • 5
  • I think there's an inherent problem with Django2 and session usage with the rest framework. The values supported in SESSION_COOKIE_SAMESITE for Django2 are not complete. Django 3 and Django 4 have resolved these issues. I would suggest upgrading to Django3 or Django 4 – Druhin Bala Mar 18 '22 at 14:30

2 Answers2

0

From what I can see, you are getting and setting the request session with the correct syntax.

e.g.

request.session.get('KEY') # for get
request.session['KEY'] = 1 # for set

Here's another related post about getting/setting items in the cache.

It's difficult to say what your failure is with the given information.

I have a couple questions about your setup that could maybe help clarify for others to help answer your issue.

  • Are you using a database-backed session? If so, have you made sure to run migrate?
  • Are you running a cache with a cache-backed session?
  • Are you setting SESSION_COOKIE_AGE to a very low value?
MrPooh
  • 59
  • 1
  • 5
  • answer is no to all of your questions. Is there any other way rather then using session – dev Feb 17 '21 at 07:10
  • I'm not sure what you're asking here. Your original post is asking about why your session is not working to get/set items from the session. – MrPooh Feb 17 '21 at 14:38
  • Concerning no to all of the questions, what have you set `SESSION_ENGINE` to currently? By default it is set to the database. – MrPooh Feb 17 '21 at 14:40
-1

You were setting the self.request.session, instead you needed to set the request.session.

class ClView(GenericAPIView):

    def get(self, request, *args, **kwargs):
        # Get Method Code
    def post(self, request, *args, **kwargs):
        cid = request.data['id'] 
        request.session['myid'] = cid
        request.session.modified = True
        return Response(status=status.HTTP_202_ACCEPTED)
class MainView(APIView):
    def get(self, request, *args, **kwargs):
        cid = request.session.get('myid')
        return Response({"id":cid})
Agyey Arya
  • 240
  • 1
  • 8