Login & Logout Views
Use Django's built-in auth views for login and logout.
Django provides ready-made views for authentication. Include django.contrib.auth.urls to get login, logout, and password-reset routes, then supply a registration/login.html template.
Under the hood these use the login() and logout() helper functions.
Example
# mysite/urls.py
from django.urls import path, include
urlpatterns = [
path("accounts/", include("django.contrib.auth.urls")),
]
# templates/registration/login.html
# <form method="post">{% csrf_token %}{{ form.as_p }}
# <button>Log in</button></form>
# settings.py
# LOGIN_REDIRECT_URL = "/"When to use it
- A developer uses Django's built-in LoginView to add a working login page by just wiring up the URL.
- A developer uses the login() function in a custom view to authenticate a user after verifying their credentials.
- A developer configures LOGIN_REDIRECT_URL in settings so users land on their dashboard after logging in.
More examples
Use built-in LoginView
Registers login and logout views; LoginView handles authentication, LogoutView ends the session.
# urls.py
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import path
urlpatterns = [
path("login/", LoginView.as_view(template_name="accounts/login.html"), name="login"),
path("logout/", LogoutView.as_view(next_page="home"), name="logout"),
]Custom login view with authenticate()
Uses authenticate() to verify credentials and login() to start the session in a custom view.
from django.contrib.auth import authenticate, login
def custom_login(request):
if request.method == "POST":
user = authenticate(
request,
username=request.POST["username"],
password=request.POST["password"],
)
if user:
login(request, user)
return redirect("dashboard")
return render(request, "accounts/login.html")Configure redirect URLs
Sets where Django sends users after login, logout, and when they access a protected URL unauthenticated.
# settings.py
LOGIN_URL = "/accounts/login/"
LOGIN_REDIRECT_URL = "/dashboard/"
LOGOUT_REDIRECT_URL = "/"
Discussion