🎓 A1Learner
🔍
0 of 50 lessons completed

Django Login and Logout

Login checks a name and password and marks the reader as logged in. Logout clears that mark.

Check the name and password

authenticate checks the posted name and password. A match gives back the user.

name = request.POST.get("name", "")
word = request.POST.get("word", "")
user = authenticate(request, username=name, password=word)
if user is not None:
    auth_login(request, user)
    return HttpResponse("Logged in as " + user.username)

Greet the logged-in user

request.user holds the logged-in user. Guest is the greeting when nobody logged in.

def hello(request):
    if request.user.is_authenticated:
        return HttpResponse("Hello, " + request.user.username + "!")
    return HttpResponse("Hello, Guest!")

Log out

logout clears the logged-in mark. The next greeting is for a guest.

def logout_view(request):
    auth_logout(request)
    return HttpResponse("Logged out")

Log in, then log out

The test client logs in as sana and shows the greeting. It then logs out and shows the guest greeting.

client = Client()
print(client.post("/login/", {"name": "sana", "word": "secret123"}).content.decode())
print(client.get("/hello").content.decode())
print(client.get("/logout/").content.decode())
print(client.get("/hello").content.decode())

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    INSTALLED_APPS=[
        "django.contrib.contenttypes",
        "django.contrib.auth",
        "django.contrib.sessions",
    ],
    MIDDLEWARE=[
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
    ],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
    LOGIN_URL="/login/",
)
django.setup()

from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.models import User
from django.core.management import call_command
from django.http import HttpResponse
from django.urls import path
from django.test import Client


def login_view(request):
    if request.method == "POST":
        name = request.POST.get("name", "")
        word = request.POST.get("word", "")
        user = authenticate(request, username=name, password=word)
        if user is not None:
            auth_login(request, user)
            return HttpResponse("Logged in as " + user.username)
        return HttpResponse("Wrong name or password")
    return HttpResponse("Show the login form")


def hello(request):
    if request.user.is_authenticated:
        return HttpResponse("Hello, " + request.user.username + "!")
    return HttpResponse("Hello, Guest!")


def logout_view(request):
    auth_logout(request)
    return HttpResponse("Logged out")


urlpatterns = [path("login/", login_view), path("hello", hello), path("logout/", logout_view)]

call_command("migrate", verbosity=0)
User.objects.create_user("sana", password="secret123")

client = Client()
print(client.post("/login/", {"name": "sana", "word": "wrong"}).content.decode())
print(client.post("/login/", {"name": "sana", "word": "secret123"}).content.decode())
print(client.get("/hello").content.decode())
print(client.get("/logout/").content.decode())
print(client.get("/hello").content.decode())

Key points

  • authenticate checks a name and password.
  • authenticate gives back the user or None.
  • login marks the reader as logged in.
  • logout clears the logged-in mark.
  • request.user holds the logged-in user.
  • Login is the check that marks a reader as logged in.

In this example, the setup lines configure Django. The program runs migrations first and makes a user named sana. The login view checks the posted name and password with authenticate. A wrong password gets a message. A right password logs the reader in. The hello view greets the logged-in name or Guest. Logout clears the mark. The prints show the wrong-password message, the login, both greetings, and the logout.

Note

A wrong password gives back None, not an error.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does authenticate give back for a wrong password?