Login with authenticate and login (FBV)
A snippet showing how to log in users using authenticate() and login() in a function-based view.
# views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from django.contrib import messages
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home') # Redirect to homepage after login
else:
messages.error(request, 'Invalid username or password.')
return render(request, 'login.html')
# templates/login.html
<form method="POST">
<% csrf_token %>
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
</form>
<% if messages %>
<% for message in messages %>
<p>{{ message }}</p>
<% endfor %>
<% endif %>
Explanation:
-
authenticate()checks if the provided credentials are correct. -
login()logs the user in by creating a session. -
messagesshows feedback if login fails. - CSRF token is required for form security.
- Redirects to
'home'if login is successful.
- Category Authentication & Authorization
- Total Views 1618
- Last Modified 12 September, 2025
- Tags #login #authentication #fbv #auth
Next snippet