Django

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

You may also like...

Leave a Reply

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