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 WebsiteIn 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:
Listing 15.3. Imports and the Definition of the logout_user() Function in the iFriends/Home/views.py File
|