Authentication with Django – Login and Logout
π Introduction
After user registration, the next step is authentication:
- login
- logout
- restricting access to certain pages
Django provides built-in functions for this:
authenticate()login()logout()@login_required
π― Program Statement
π Implement login, logout, and protected page using authentication.
π§ Concept
This program uses:
- Django authentication system
- session management
- protected routes
βοΈ Step 1: Create Login Form
π File: forms.py
πΉ Path:
myproject/myapp/forms.py
πΉ Code:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(label='Enter Username')
password = forms.CharField(label='Enter Password', widget=forms.PasswordInput)
βοΈ Step 2: Create Views
π File: views.py
πΉ Path:
myproject/myapp/views.py
πΉ Code:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import LoginForm
# LOGIN VIEW
def login_user(request):
error_message = None
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard')
else:
error_message = "Invalid username or password"
else:
form = LoginForm()
return render(request, 'login.html', {
'form': form,
'error_message': error_message
})
# LOGOUT VIEW
def logout_user(request):
logout(request)
return redirect('login')
# PROTECTED PAGE
@login_required(login_url='login')
def dashboard(request):
return render(request, 'dashboard.html')
π§ Explanation
authenticate()checks username/passwordlogin()creates user sessionlogout()ends session@login_requiredrestricts access
βοΈ Step 3: URL Mapping
π File: urls.py
πΉ Path:
myproject/myproject/urls.py
πΉ Code:
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login_user, name='login'),
path('logout/', views.logout_user, name='logout'),
path('dashboard/', views.dashboard, name='dashboard'),
]
βοΈ Step 4: Create Templates
π File: login.html
πΉ Path:
myproject/templates/login.html
πΉ Code:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login Page</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
<hr>
{% if error_message %}
<h3 style="color:red;">{{ error_message }}</h3>
{% endif %}
</body>
</html>
π File: dashboard.html
πΉ Path:
myproject/templates/dashboard.html
πΉ Code:
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Welcome to Dashboard</h1>
<p>You are logged in successfully.</p>
<a href="/logout/">Logout</a>
</body>
</html>
βοΈ Step 5: Update Settings
π File: settings.py
Add:
LOGIN_URL = '/login/'
π§ Explanation
If user is not logged in, Django will redirect to login page.
βοΈ Step 6: Run Server
python manage.py runserver
π Step 7: Output
π Login Page:
http://127.0.0.1:8000/login/
β Valid Login:
- Redirects to dashboard
β Invalid Login:
Invalid username or password
π Dashboard (Protected):
http://127.0.0.1:8000/dashboard/
β Without Login:
π Redirected to login page
π Logout:
http://127.0.0.1:8000/logout/
π Session ends
π§ How It Works
- User enters credentials
authenticate()verifies userlogin()creates session- User accesses protected page
@login_requiredensures securitylogout()destroys session
π₯ Key Concepts
Authenticate User
authenticate(request, username=username, password=password)
Login User
login(request, user)
Logout User
logout(request)
Protected View
@login_required
β οΈ Common Errors
β Forgot @login_required
π Page becomes publicly accessible
β Wrong redirect name
return redirect('dashboard')
Must match URL name
β Forgot CSRF token
{% csrf_token %}
β Login always failing
Check:
- user exists
- password correct
- migrated database
β LOGIN_URL not set
Add in settings:
LOGIN_URL = '/login/'
π§ͺ Practice Questions
- Display username in dashboard
- Add logout confirmation
- Redirect after login
- Restrict multiple pages
- Add remember me option
π€ Viva Questions & Answers
1. What is authentication in Django?
Authentication is the process of verifying a user’s identity using username and password.
2. What does authenticate() do?
It checks if the given username and password are valid.
3. What is login() used for?
It logs in the user by creating a session.
4. What is logout() used for?
It logs out the user by destroying the session.
5. What is @login_required?
It restricts access to a view only for logged-in users.
6. What happens if user is not logged in?
They are redirected to the login page.
7. What is session in Django?
Session stores user data between requests.
8. Can we protect multiple pages?
Yes, by using @login_required on each view.
9. Why is authentication important?
It ensures only authorized users can access certain features.
10. What is LOGIN_URL?
It defines the URL where users are redirected if not logged in.
π Navigation
π Next Post: CRUD using Class-Based Views
π Back to List: Django Programs (60 Questions with Solutions)
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET

[…] π Next Post: Implement Login, Logout, and Protected Page using Authenticationπ Back to List: Django Programs (60 Questions with Solutions) […]