Previous Page Next Page

Adding Logout Functionality

Now that you have given users a way to log into the website, you likely will want to give them a way to log out. Django provides the django.contrib.auth.logout() function to handle removing the logged-in user from the session.

The logout() function takes an HttpRequest object as its only parameter and decouples the logged-in User object from the session. The following example shows how to use the logout() function in a view:

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("somelogoutULR")

By the Way

The logout() function does not raise any errors if the user wasn't logged in, so you don't need to verify that it is being called on a request that has a logged-in user.


Try It Yourself: Add Logout Functionality to Your Website

In this section, you will create a user_logout() view function that logs out the current user. Follow these steps to create and enable the logout view so that it redirects the user to the user_login() view:

1.
Open the iFriends/Home/views.py file in an editor.

2.
Add logout to the following import statement to import the logout() function:

from django.contrib.auth import authenticate, login, logout

3.
Add the following logout_user() function, shown in Listing 15.3, to log out the user and redirect the response to the user_login() view:

from django.contrib.auth import authenticate, login, logout
. . .
def logout_user(request):
    logout(request)
    return HttpResponseRedirect('/Login')

4.
Save the iFriends/Home/views.py file.

5.
Open the iFriends/urls.py file in an editor.

6.
Add the following URL pattern to enable the new logout_user() view:

(r'^Logout/$', 'iFriends.Home.views.logout_user'),

7.
Save the iFriends/urls.py file.

8.
Access the following URL in a web browser. It should log you out of the website. (You can confirm this by trying to access the admin interface.)

http://127.0.0.1:8000/Logout/

Listing 15.3. Imports and the Definition of the logout_user() Function in the iFriends/Home/views.py File

from django.contrib.auth import authenticate, login, logout
. . .
def logout_user(request):
    logout(request)
    return HttpResponseRedirect('/Login')


Previous Page Next Page