๐ 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
