Marcolac
Marcolac

Reputation: 931

Expiry a specific value of a session in Django

I display a newsletter pop up in my website when the visitors see a specific page. I would like to display it only every two weeks. In the docs, I found this about sessions and set_expiry.

So I tried to do the following (using 5 seconds for the example instead of two weeks) :

def example(request):
    request.session['newsletter'] = 'test'
    request.session.set_expiry(5)

But the problems are :

1 - set_expiry only works if there are 5 seconds of inactivity (in this case it means without session modification). In my case I would like to disable this behavior.

2 - set_expiry clears all values of the session. I would like it to clear only the newsletter value.

I can not find a way to accomplish that. Is there a proper way to do it ? Thanks for the help !

Upvotes: 1

Views: 812

Answers (1)

mimo
mimo

Reputation: 2629

set_expiry deals with the expiration time of the whole session, not just the variable 'newsletter'.

In your case, the best to do is probably to create a session by making sure that it will live at least for two weeks. You should therefore set expiration to two weeks at least. Then you can use this session to do all sort of stuff, including the newsletter business. When processing a request, do this:

  • If the session does not have a 'newsletter' field, create it and set it to datetime.now(). Also display the newsletter pop-up.
  • If it has a newsletter field younger than two weeks, do nothing.
  • If it has a newsletter field of two weeks or more, display the pop-up and set again the field to datetime.now().

Upvotes: 1

Related Questions