Introduction
We can use client-side cookies to store valuable data for the web app. We can use client-side cookies to store various data valid for our web app. This leads to many security loopholes depending on the importance of the data we want to save.
Django offers a session framework for handling cookies for security reasons. Data is saved on the server-side (as in a database), and the client-side cookie has a session ID for identification. Sessions are also useful in avoiding situations when the user's browser is set to "deny all cookies."
Setting Up Sessions
The project settings are where you enable sessions in Django. In Python, add some lines to the INSTALLED APPS and MIDDLEWARE CLASSES options. This should be done when the project is created, but it's always good to be prepared, thus MIDDLEWARE CLASSES should have MIDDLEWARE CLASSES.
'django.contrib.sessions.middleware.SessionMiddleware'
And INSTALLED_APPS should have −
'django.contrib.sessions'
Django saves session information in the database (Django_session table or collection). Still, we can configure the engine to store information using other ways like: in a file or the cache.
When the session is enabled, every request (first argument of any Django view) has a session (dict) attribute.
Let's make a basic example to show how to create and store sessions.On a login page, let us keep the username in a cookie so, if not signed out, you won't see the login form when accessing our login page. Let's make the Django Cookies handling login system more safe by keeping cookies on the server.
First, let's alter our login view such that our username cookie is saved server-side.
def login(request):
username = 'not logged in'
if request.method == 'POST':
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
request.session['username'] = username
else:
MyLoginForm = LoginForm()
return render(request, 'loggedin.html', {"username" : username}
Then we'll make a formView view for the login form, which will hide the form if a cookie is set.
def formView(request):
if request.session.has_key('username'):
username = request.session['username']
return render(request, 'loggedin.html', {"username" : username})
else:
return render(request, 'login.html', {})
Now we'll edit the url.py file to update the URL to match our new view.
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns('myapp.views',
url(r'^connection/','formView', name = 'loginform'),
url(r'^login/', 'login', name = 'login'))
we'll see the following screen when you go to /myapp/connection.

And then we will get redirected to the following page −

If you try to enter /myapp/connection again, you'll be taken straight to the second screen.
Let's make a straightforward logout view that clears our cookie
def logout(request):
try:
del request.session['username']
except:
pass
return HttpResponse("<strong>You are logged out.</strong>")
In myapp/url.py, match it with a logout URL.
url(r'^logout/', 'logout', name = 'logout'),
If you browse to /myapp/logout now, you'll see something like this:

If you go back to /myapp/connection, you'll see the login form .




