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.
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.
<!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.
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.
<form action="{% url 'logout' %}" method="post">
{% csrf_token %}
<button type="submit">Log out</button>
</form>Read the official Django documentation for details and more examples.