Django User Authentication Tutorial

Learn how to implement user authentication in Django with step-by-step instructions

Project Setup (প্রজেক্ট সেটআপ)

First, create a new Django project and app if you haven't already:

# Create a new Django project
django-admin startproject myproject
cd myproject

# Create a home app
python manage.py startapp home
প্রথমে Django project এবং app তৈরি করুন উপরের commands ব্যবহার করে
First, create a Django project and app using the commands above

Template Structure (টেমপ্লেট স্ট্রাকচার)

Create the following directory structure for templates:

home/
  templates/
    home/
      registration/
        signup.html
        login.html
        base.html

Tip (টিপ)

Create a base.html template for common structure to avoid code repetition.

একটি base.html টেমপ্লেট তৈরি করুন যাতে common structure থাকে, code repetition এড়ানোর জন্য

SignUp Template (সাইনআপ টেমপ্লেট)

Create the signup.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sign Up</title>
</head>
<body>
  <h2>Sign Up</h2>
  <form method="post">
    
    
    <button type="submit">Sign Up</button>
  </form>
  <p>Already have an account?
    <a href="/login/">Login here</a>
  </p>
</body>
</html>

Template Explanation (টেমপ্লেট ব্যাখ্যা):

  • এই template টি user registration করার form দেখায় (This template displays the user registration form)
  • CSRF attack থেকে protection দেয় (provides protection against CSRF attacks)
  • Django form কে paragraph tags এর মধ্যে render করে (renders the Django form within paragraph tags)
  • Form submit করলে POST request হবে এবং Django signup view handle করবে (When the form is submitted, a POST request will be made and handled by the Django signup view)

Login Template (লগইন টেমপ্লেট)

Create the login.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Login</title>
</head>
<body>
  <h2>Login</h2>
  <form method="post">
    
    
    <button type="submit">Login</button>
  </form>
  <p>Don't have an account?
    <a href="/signup/">Sign up here</a>
  </p>
</body>
</html>

Template Explanation (টেমপ্লেট ব্যাখ্যা):

  • এই template টি user login করার form দেখায় (This template displays the user login form)
  • এটি Django এর built-in LoginForm ব্যবহার করে (It uses Django's built-in LoginForm)
  • User credentials validate করার পর session create হবে (After validating user credentials, a session will be created)
  • Signup page-এ link যুক্ত আছে নতুন user এর জন্য (There's a link to the signup page for new users)

Views.py (ভিউস ফাইল)

Add the signup function to your views.py:

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages

def signup(request):
  if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
      user = form.save()
      username = form.cleaned_data.get('username')
      messages.success(request, f'Account created for {username}!')
      login(request, user)
      return redirect('index')
    else:
      messages.error(request, 'Please correct the error below.')
  else:
    form = UserCreationForm()
  return render(request, 'registration/signup.html', {'form': form})

View Function Explanation (ভিউ ফাংশন ব্যাখ্যা):

  • যখন POST request আসে, তখন form validation করা হয় (When a POST request comes, form validation is performed)
  • Form valid হলে user create হয় database-এ (If the form is valid, a user is created in the database)
  • User কে authenticate এবং login করা হয় (The user is authenticated and logged in)
  • সবশেষে user কে index page-এ redirect করা হয় (Finally, the user is redirected to the index page)
  • GET request এর জন্য খালি form show করা হয় (For GET requests, an empty form is shown)

URLs Configuration (ইউআরএল কনফিগারেশন)

Configure URLs in your urls.py file:

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
  path('signup/', views.signup, name='signup'),
  path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
  path('logout/', auth_views.LogoutView.as_view(next_page='index'), name='logout'),
  path('password-reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset.html'), name='password_reset'),
]

URLs Explanation (ইউআরএল ব্যাখ্যা):

  • signup/ route টি আমাদের custom signup view কে handle করে (The signup/ route handles our custom signup view)
  • login/ route টি Django এর built-in LoginView ব্যবহার করে (The login/ route uses Django's built-in LoginView)
  • logout/ route টি user কে logout করে এবং index page-এ redirect করে (The logout/ route logs out the user and redirects to the index page)
  • প্রতিটি route এর একটি নাম আছে template এ ব্যবহার করার জন্য (Each route has a name for use in templates)

Settings Configuration (সেটিংস কনফিগারেশন)

Make sure to configure your settings.py properly:

# Add your app to INSTALLED_APPS
INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'home', # Your app
]

# Set login redirect URL
LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'index'

# Email backend for password reset (development)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Important Notes (গুরুত্বপূর্ণ নোট):

  • Template files টি সঠিক location এ create করতে হবে (Template files must be created in the correct location)
  • Django এর built-in authentication system ব্যবহার করার জন্য django.contrib.auth app installed থাকতে হবে (The django.contrib.auth app must be installed to use Django's built-in authentication system)
  • User authentication এর জন্য database migrate করতে ভুলবেন না (Don't forget to migrate the database for user authentication)
  • Production environment এ SSL ব্যবহার করুন security এর জন্য (Use SSL in production environment for security)

Testing the Authentication (অথেন্টিকেশন টেস্ট করা)

নিচের commands গুলো run করে test করুন: (Run the following commands to test:)

# Run migrations
python manage.py migrate

# Create a superuser
python manage.py createsuperuser

# Run the development server
python manage.py runserver

এরপর browser এ গিয়ে http://127.0.0.1:8000/signup/ এ visit করে signup test করুন (Then visit http://127.0.0.1:8000/signup/ in your browser to test signup)

Back to Home Back