← All tutorials

Authentication / 8 MIN READ

Add login and logout to your Django site

Use Django's authentication views, add a login template, and protect a private page.

01 Connect authentication URLs

Use the starter project, apply the default migrations, and create a user with createsuperuser if you have not already. In config/urls.py, import include and add the accounts route to urlpatterns.

Code example
from django.urls import include, path

# Add inside urlpatterns:
path("accounts/", include("django.contrib.auth.urls")),

02 Create the login template

Save this as core/templates/registration/login.html. Django's LoginView supplies the form. The hidden next value preserves the destination when someone reaches login from a protected page.

Code example
<!doctype html>
<html lang="en"><title>Log in</title>
<h1>Log in</h1>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <input type="hidden" name="next" value="{{ next }}">
  <button type="submit">Log in</button>
</form>
</html>

03 Choose destinations

Add these settings to config/settings.py. They control where users go after signing in or signing out when a more specific destination has not been supplied.

Code example
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

04 Protect a page and add logout

Apply @login_required to a view that needs an authenticated user. For logout, place the form below in your base template. Logging out changes state, so use POST with a CSRF token. Test login at /accounts/login/ and verify that a private page redirects when signed out.

Code example
<form action="{% url 'logout' %}" method="post">
  {% csrf_token %}
  <button type="submit">Log out</button>
</form>
Keep exploring

Read the official Django documentation for details and more examples.