Logging Out
Part of the Users and Accounts section of Coddy's Django journey. Lesson 3 of 16.
A signed in user has no way to sign out. The same include() added /accounts/logout/, named logout: it ends the session, so the cookie no longer points to a user.
A plain link will not do. A link sends a GET, and a GET should never change anything: a page could hide an image whose address is your logout URL and log you out. So LogoutView accepts only POST, and answers a GET with 405 Method not allowed.
A button that changes something is a small POST form, even with no fields. Its action names the URL it posts to, so it can sit on any page:
<form method="post" action="{% url 'cart:empty' %}">
{% csrf_token %}
<button type="submit">Empty cart</button>
</form>After logging out, Django redirects to LOGOUT_REDIRECT_URL.
Challenge
Easy- In
base.html, underSigned in as ..., aLog outbutton logs the user out. - After logging out, the visitor lands on
/.
Press Run, log in as ada (password coddy-pass-123), then press Log out.
Try it yourself
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}Notes{% endblock %}</title>
<link rel="stylesheet" href="{% static 'notes/style.css' %}">
</head>
<body>
<header>
<a class="brand" href="{% url 'notes:list' %}">Notes</a>
<nav>
<a href="{% url 'notes:create' %}">New note</a>
</nav>
<div class="account">
{% if user.is_authenticated %}
<p>Signed in as {{ user.username }}</p>
{% else %}
<p>You are not signed in.</p>
<a href="{% url 'login' %}">Log in</a>
{% endif %}
</div>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Users and Accounts
Practice on your own: Django playground