6. Sessions framework - LiVanych/locallibrary GitHub Wiki
Sessions were enabled automatically when we created the skeleton website.
The configuration is set up in the INSTALLED_APPS
and MIDDLEWARE
sections of the project
file (locallibrary/locallibrary/settings.py
), as shown below:
INSTALLED_APPS = [
...
'django.contrib.sessions',
....
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
....
As a simple real-world example we'll update our library to tell the current user how many times they have visited the LocalLibrary home page.
Open /locallibrary/catalog/views.py
, and make the changes shown below.
def index(request):
...
num_authors = Author.objects.count() # The 'all()' is implied by default.
...
# Number of visits to this view, as counted in the session variable.
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
context = {
...
...
'num_visits': num_visits,
}
# Render the HTML template index.html with the data in the context variable.
return render(request, 'index.html', context=context)
Add the line seen at the bottom of the following block to your main HTML template
(/locallibrary/catalog/templates/index.html
) at the bottom of the "Dynamic content
"
section to display the context variable:
<h2>Dynamic content</h2>
<p>The library has the following record counts:</p>
<ul>
<li><strong>Books:</strong> {{ num_books }}</li>
<li><strong>Copies:</strong> {{ num_instances }}</li>
<li><strong>Copies available:</strong> {{ num_instances_available }}</li>
<li><strong>Authors:</strong> {{ num_authors }}</li>
</ul>
<p>You have visited this page {{ num_visits }}
{% if num_visits == 1 %}
time
{% else %}
times
{% endif %}.
</p>
Save your changes and restart the test server. Every time you refresh the page, the number should update.
That's All!
How to use sessions (Django docs)