0

I have a question about refreshing sessions! When I was making sessions expire using PHP I just required sessionmaintenance.php at the top of a document, is there an easy way to do the same in a Django template, so that I don't have to do it in every view?

Example view-code:

@login_required
def index(request):
    request.session.set_expiry(30)
    testvar="Hi!"
    return render(request, 'testapp/index.html', {'testvar':testvar})

@login_required
def uploadview(request):
    request.session.set_expiry(30)
    etc...

What I'd like to do is make a base.html that looks something like this - Example template code:

{% if user.is_authenticated %}
<h6>{{ request.user.username }} {{ request.user.first_name }}</h6>
{% endif %}
{% request.session.set_expiry(30) %} 
{% block content %}
{% endblock %}

Incorporating the session refresh into my base.html so that my view-code looks cleaner and I don't have to repeat myself as much.

Marcus Grass
  • 1,043
  • 2
  • 17
  • 38
  • This isn't the sort of thing you should do in a template; those are fur presenting data to the user. You might consider a custom middleware, for example. – Daniel Roseman Apr 15 '18 at 20:56
  • Of course you're right, I'm a bit new to Django still trying to get into best-practice, I'll look into middleware! – Marcus Grass Apr 15 '18 at 21:18
  • Take a look at [this question](https://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes), definitely you will find what you're looking for – Lemayzeur Apr 15 '18 at 22:52

1 Answers1

1

This might not be exactly what you're looking for, but have you checked out the SESSION_COOKIE_AGE parameter that's available for Django settings?

It sets the hard limit of session cookie in seconds, like so:

SESSION_COOKIE_AGE = 30
pseudoku
  • 716
  • 4
  • 11
  • In order to be immediately helpful to readers (and avoid [Linkrot](https://en.wikipedia.org/wiki/Link_rot)), we prefer answer that provide at least a solid summary of the solution directly, with links used to offer additional information. [More info on link only answers](https://meta.stackoverflow.com/tags/link-only-answers/info). – Stefan Crain Apr 15 '18 at 21:14