36

I have two views.

view1 passes an error message to view2 through a session key.

How do I delete the key after view2 is rendered? I only need it for once: redirect from view1 to view2. I dont need that message to show up after refreshing my webpage. I don't think python will continue to execute once it reaches return

I was thinking about setting an expiration timestamp but I need to ensure that it exists for at least 10-20 seconds, if the application really does that long to load (we do some server stuff with Django)? So time is not that promising.

Thanks.

CppLearner
  • 16,273
  • 32
  • 108
  • 163

3 Answers3

70

You can delete the key from the session like any other dictionary.

del request.session['your key']

You may need to mark the session as modified for it to save, depending on some of your settings.

request.session.modified = True
Collin Green
  • 2,146
  • 14
  • 12
  • 2
    Sorry. I made the whole thing so complicated. I just save it to local var, and it's done. Just delete it. Thanks. I am thinking too much. – CppLearner Mar 20 '12 at 04:15
  • 3
    If you `del` the key that is directly associated with session, and not nested like `request.session['parent_key']['child']`, then it is not required to set `request.session.modified = True` – shad0w_wa1k3r Jan 16 '18 at 14:04
30

You could also pop the key from the session. You could set the key to a variable and get rid of it at the same time:

key_variable = request.session.pop('your key')
Jonathan
  • 2,565
  • 4
  • 18
  • 25
2
if "uid" in self.request.session.keys():
    del self.request.session["uid"]
  • 2
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Abhishek Bhagate Jun 04 '20 at 18:06
  • 1
    In addition to @Abhishek's feedback, it'd be really useful to understand when and why this approach might be preferred over the accepted answer from over eight years ago. Is there a benefit to this that's e.g. permitted by recent versions of Django? – Jeremy Caney Jun 05 '20 at 00:32
  • Thanks ....i took this for my solution – Ajay Kumar Oct 05 '21 at 11:20