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/password
  • login() creates user session
  • logout() ends session
  • @login_required restricts 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

  1. User enters credentials
  2. authenticate() verifies user
  3. login() creates session
  4. User accesses protected page
  5. @login_required ensures security
  6. logout() 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

  1. Display username in dashboard
  2. Add logout confirmation
  3. Redirect after login
  4. Restrict multiple pages
  5. 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

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

1 thought on “Authentication with Django – Login and Logout

Leave a Reply

Your email address will not be published. Required fields are marked *