Skip to main content

DJANGO

 

Django Complete Syllabus for Beginners (Start to End)

This structured Django syllabus will help you go from beginner to advanced level with real-time practical experience.


📌 Module 1: Introduction to Django

🔹 What is Django?
🔹 Features of Django
🔹 Installation & Setup (Windows/Linux)
🔹 Creating a Virtual Environment
🔹 Understanding the MVT (Model-View-Template) Architecture
🔹 First Django Project & Running the Development Server

Hands-on:
✔️ Install Django and create a "Hello, World" project


📌 Module 2: Django Project Structure & Basic Concepts

🔹 Understanding Django Project Structure
🔹 Creating and Managing Django Apps
🔹 Understanding settings.py, urls.py, views.py, models.py
🔹 Working with Django Admin Panel

Hands-on:
✔️ Create a simple "About Me" webpage using Django


📌 Module 3: Django Models & Databases

🔹 Understanding Django ORM (Object-Relational Mapping)
🔹 Creating Models and Migrations
🔹 Connecting Django with SQLite, MySQL, PostgreSQL
🔹 CRUD (Create, Read, Update, Delete) Operations in Django ORM
🔹 Using Django Shell for Database Queries

Hands-on:
✔️ Create a database model for a Blog App and perform CRUD operations


📌 Module 4: Django Views & Templates

🔹 Understanding Views and Function-Based Views (FBV)
🔹 Using Template Language ({% for %}, {% if %}, etc.)
🔹 Handling Static Files (CSS, JS, Images)
🔹 Template Inheritance in Django

Hands-on:
✔️ Create a Dynamic Home Page using Django Templates


📌 Module 5: Django Forms & User Input Handling

🔹 Creating HTML Forms in Django
🔹 Handling Form Submissions (GET & POST)
🔹 Django ModelForms for Automatic Form Handling
🔹 Validating User Inputs

Hands-on:
✔️ Create a Contact Form with Input Validation


📌 Module 6: Django Authentication & User Management

🔹 User Registration & Login System
🔹 Password Reset & Change Password
🔹 Authentication with Django's Built-in User Model
🔹 Using Middleware for Authentication
🔹 User Permissions and Groups

Hands-on:
✔️ Build a User Login & Signup System


📌 Module 7: Django REST Framework (DRF) - API Development

🔹 Introduction to Django REST Framework (DRF)
🔹 Creating RESTful APIs
🔹 Serializers & Views in DRF
🔹 Authentication in API (JWT, Token-Based Auth)
🔹 Connecting Django API with Frontend (React/Angular)

Hands-on:
✔️ Build a REST API for a To-Do App


📌 Module 8: Django Deployment & Hosting

🔹 Deploying Django on Heroku, AWS, or DigitalOcean
🔹 Using Gunicorn & Nginx for Production
🔹 Working with Docker & Docker Compose
🔹 CI/CD for Django Applications

Hands-on:
✔️ Deploy a Django Application on Heroku


📌 Module 9: Advanced Django Concepts

🔹 Working with Celery for Background Tasks
🔹 Implementing Caching for Performance Optimization
🔹 WebSockets & Real-Time Chat Application
🔹 Security Best Practices in Django (XSS, CSRF, SQL Injection Prevention)

Hands-on:
✔️ Build a Real-Time Chat App with Django Channels


📌 Module 10: Final Projects

🔹 E-commerce Website (User authentication, Cart, Checkout, Payment Gateway)
🔹 Blog Application (CRUD, Comments, Categories, Tags, Search)
🔹 Job Portal (User Registration, Job Posting, Apply for Jobs)

Hands-on:
✔️ Choose one of the projects and deploy it online


📌 Module 1: Introduction to Django


🔹 What is Django?

Django is a high-level Python web framework that allows developers to build secure, scalable, and maintainable web applications quickly. It follows the "batteries-included" philosophy, meaning it comes with built-in features such as authentication, ORM, form handling, and more.

Key Points:

  • Written in Python
  • Follows MVT (Model-View-Template) architecture
  • Provides built-in security features
  • Used by companies like Instagram, Pinterest, and Mozilla
  • Makes web development faster and more efficient

🔹 Example of Django in Action:
Django simplifies web development. For example, instead of manually handling database queries, Django lets you use Python code:

python
from django.db import models class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True)

This automatically creates a database table! 🚀


🔹 Features of Django

Django provides many features that make web development easier and more efficient.

Key Features:

  1. Fast Development: Pre-built components allow rapid development.
  2. Security: Protects against SQL Injection, XSS, CSRF, and Clickjacking.
  3. Scalability: Can handle high-traffic applications like Instagram.
  4. Built-in Admin Panel: Automatically generates an admin interface.
  5. ORM (Object-Relational Mapping): Allows interaction with the database using Python instead of SQL.
  6. Cross-Platform: Runs on Windows, macOS, and Linux.
  7. Reusable Components: Encourages code reusability through Django Apps.

💡 Fun Fact: Django was named after jazz guitarist Django Reinhardt! 🎸


🔹 Installation & Setup (Windows/Linux)

Step 1: Install Python

Before installing Django, make sure Python is installed.
Run the following command to check Python version:

bash
python --version

If not installed, download Python from: https://www.python.org/downloads/


Step 2: Install Django

To install Django, use the following command:

bash
pip install django

Verify installation:

bash
django-admin --version

🔹 Creating a Virtual Environment

A virtual environment helps manage dependencies and keeps projects isolated.

Steps to Create a Virtual Environment:

1️⃣ Navigate to your project directory:

bash
cd path/to/project

2️⃣ Create a virtual environment:

bash
python -m venv myenv

3️⃣ Activate the virtual environment:

  • Windows:
    bash
    myenv\Scripts\activate
  • Linux/macOS:
    bash
    source myenv/bin/activate

4️⃣ Install Django inside the virtual environment:

bash
pip install django

💡 Tip: Always activate the virtual environment before working on Django projects.


🔹 Understanding the MVT (Model-View-Template) Architecture

Django follows the MVT (Model-View-Template) architecture, which is similar to MVC (Model-View-Controller).

Components of MVT:

1️⃣ Model (M) – Handles database operations (Database Layer)
2️⃣ View (V) – Contains logic and processes requests (Business Logic Layer)
3️⃣ Template (T) – Controls the frontend and UI (Presentation Layer)

📌 MVT Flow:

  1. The User requests a webpage (e.g., /home).
  2. View processes the request and interacts with the Model.
  3. The Model retrieves data from the database and sends it back.
  4. The Template displays the data in HTML format.

Example:

  • models.py (Model)
    python
    from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.FloatField()
  • views.py (View)
    python
    from django.shortcuts import render from .models import Product def product_list(request): products = Product.objects.all() return render(request, 'product_list.html', {'products': products})
  • product_list.html (Template)
    html
    <h1>Product List</h1> <ul> {% for product in products %} <li>{{ product.name }} - ${{ product.price }}</li> {% endfor %} </ul>

🔹 First Django Project & Running the Development Server

Step 1: Create a New Django Project

Run the following command:

bash
django-admin startproject myproject

This creates a folder myproject/ with the following structure:

markdown
myproject/ │── manage.py │── myproject/ │ │── __init__.py │ │── settings.py │ │── urls.py │ │── wsgi.py │ │── asgi.py

Step 2: Run the Development Server

Navigate into the project folder and run:

bash
python manage.py runserver

📌 Output:

bash
Starting development server at http://127.0.0.1:8000/

Open http://127.0.0.1:8000/ in your browser. You should see the Django welcome page 🎉


Step 3: Create a New Django App

Inside the project, create an app:

bash
python manage.py startapp myapp

This creates a folder myapp/ with files for models, views, templates, etc.

Register the app in settings.py

python
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # Add your app here ]

Step 4: Create a Simple View

Edit myapp/views.py:

python
from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!")

Edit myproject/urls.py:

python
from django.contrib import admin from django.urls import path from myapp.views import home urlpatterns = [ path('admin/', admin.site.urls), path('', home), # Map the home function to the root URL ]

🔹 Restart the server and visit http://127.0.0.1:8000/ to see "Hello, Django!" 🎉


📌 Module 2: Django Project Structure & Basic Concepts

This module covers the structure of a Django project, how to create and manage Django apps, and how different components like settings.py, urls.py, views.py, and models.py work together.


🔹 Understanding Django Project Structure

When you create a new Django project using:

bash
django-admin startproject myproject

It generates the following structure:

markdown
myproject/ │── manage.py │── myproject/ │ │── __init__.py │ │── settings.py │ │── urls.py │ │── asgi.py │ │── wsgi.py

Explanation of Each File:

FileDescription
manage.pyA command-line utility to run Django commands (e.g., runserver, migrate).
settings.pyContains configurations like database settings, installed apps, middleware, etc.
urls.pyDefines URL routing for the project.
asgi.pyUsed for handling asynchronous requests (not mandatory for beginners).
wsgi.pyUsed to deploy Django applications with WSGI-compatible servers.
__init__.pyMarks this directory as a Python package.

🔹 Creating and Managing Django Apps

A Django project can have multiple apps. An app is a self-contained module that handles a specific functionality (e.g., a blog, an authentication system, etc.).

Create a New App:

Navigate to the project directory and run:

bash
python manage.py startapp myapp

This creates a folder myapp/ with the following structure:

markdown
myapp/ │── migrations/ │── __init__.py │── admin.py │── apps.py │── models.py │── tests.py │── views.py

Explanation of Each File:

FileDescription
models.pyDefines the database structure.
views.pyContains logic to handle user requests.
admin.pyConfigures the Django admin panel.
migrations/Stores database migration files.
tests.pyUsed for writing test cases.

💡 Tip: Every time you create a new app, register it in settings.py under INSTALLED_APPS:

python
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # Add your app here ]

🔹 Understanding settings.py, urls.py, views.py, models.py

1️⃣ settings.py (Configuration File)

settings.py contains all project configurations, including:

  • Database settings
  • Installed apps
  • Middleware
  • Template and static files configurations

Example: Changing the default timezone

python
TIME_ZONE = 'Asia/Kolkata' # Set to Indian time

2️⃣ urls.py (URL Routing)

Defines how URLs map to views.

Example:

python
from django.contrib import admin from django.urls import path from myapp.views import home urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), # Default home page ]

3️⃣ views.py (Handling Requests)

Contains Python functions that process HTTP requests.

Example:

python
from django.http import HttpResponse def home(request): return HttpResponse("Welcome to My Django Site!")

4️⃣ models.py (Database Models)

Defines the database structure using Django ORM.

Example:

python
from django.db import models class Profile(models.Model): name = models.CharField(max_length=100) bio = models.TextField()

Run the migration after defining models:

bash
python manage.py makemigrations python manage.py migrate

🔹 Working with Django Admin Panel

Django provides a built-in admin panel for managing database models.

Step 1: Create a Superuser

Run the following command:

bash
python manage.py createsuperuser

Enter a username, email, and password.


Step 2: Register a Model in Admin Panel

Edit admin.py:

python
from django.contrib import admin from .models import Profile admin.site.register(Profile) # Register the Profile model

Step 3: Start the Server & Access Admin Panel

bash
python manage.py runserver

Visit http://127.0.0.1:8000/admin/ and log in with the superuser credentials. 🎉


✅ Hands-on: Create a Simple "About Me" Webpage Using Django

Step 1: Create a View in views.py

Edit myapp/views.py:

python
from django.shortcuts import render def about(request): return render(request, 'about.html')

Step 2: Create a Template in myapp/templates/

Create a templates folder inside myapp/, then create an about.html file:

html
<!DOCTYPE html> <html> <head> <title>About Me</title> </head> <body> <h1>About Me</h1> <p>Hello, I'm learning Django!</p> </body> </html>

Step 3: Add a URL Pattern in urls.py

Edit myproject/urls.py:

python
from django.contrib import admin from django.urls import path from myapp.views import about urlpatterns = [ path('admin/', admin.site.urls), path('about/', about, name='about'), ]

Step 4: Run the Server and Visit the Page

bash
python manage.py runserver

Go to http://127.0.0.1:8000/about/ and see your "About Me" page. 🚀

📌 Module 3: Django Models & Databases

In this module, you'll learn about Django's Object-Relational Mapping (ORM), how to create models, run migrations, connect databases, and perform CRUD operations using Django ORM.


🔹 Understanding Django ORM (Object-Relational Mapping)

Django ORM (Object-Relational Mapping) allows you to interact with a database using Python code instead of writing raw SQL queries.

💡 Key Features of Django ORM:
✅ Works with multiple databases (SQLite, MySQL, PostgreSQL, etc.).
✅ Automatically creates database tables from Python models.
✅ Provides a high-level Python API to perform queries.


🔹 Creating Models and Migrations

A model in Django is a Python class that defines a table in the database.

Step 1: Define a Model

Open models.py in your Django app (myapp/models.py) and define a BlogPost model:

python
from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() author = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title

Step 2: Run Migrations

Django uses migrations to apply model changes to the database.

1️⃣ Create Migration Files

bash
python manage.py makemigrations

2️⃣ Apply Migrations to Database

bash
python manage.py migrate

Now, Django will create a BlogPost table in the database. 🚀


🔹 Connecting Django with SQLite, MySQL, PostgreSQL

By default, Django uses SQLite, but you can change it to MySQL or PostgreSQL.

SQLite (Default Database)

Django's default database is SQLite and is configured in settings.py:

python
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / "db.sqlite3", } }

MySQL Configuration

Install the MySQL client for Python:

bash
pip install mysqlclient

Modify settings.py:

python
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabase', 'USER': 'root', 'PASSWORD': 'password123', 'HOST': 'localhost', 'PORT': '3306', } }

Run migrations again:

bash
python manage.py migrate

PostgreSQL Configuration

Install the PostgreSQL driver:

bash
pip install psycopg2

Modify settings.py:

python
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'postgres', 'PASSWORD': 'password123', 'HOST': 'localhost', 'PORT': '5432', } }

Run migrations:

bash
python manage.py migrate

🔹 CRUD (Create, Read, Update, Delete) Operations in Django ORM

Django ORM allows you to perform CRUD operations easily.

1️⃣ Create Data (Insert Records)

Inside views.py, create a new BlogPost record:

python
from myapp.models import BlogPost new_post = BlogPost.objects.create( title="My First Blog", content="This is my first blog post using Django ORM.", author="Neelamohan" ) print(new_post.id) # Print the new record's ID

2️⃣ Read Data (Retrieve Records)

Fetch all blog posts:

python
posts = BlogPost.objects.all() # Get all records for post in posts: print(post.title, post.author)

Fetch a single blog post by ID:

python
post = BlogPost.objects.get(id=1) print(post.title, post.content)

3️⃣ Update Data

Update a blog post's title:

python
post = BlogPost.objects.get(id=1) post.title = "Updated Blog Title" post.save()

4️⃣ Delete Data

Delete a blog post:

python
post = BlogPost.objects.get(id=1) post.delete()

🔹 Using Django Shell for Database Queries

Django provides an interactive shell to test queries:

Open Django Shell:

bash
python manage.py shell

Perform CRUD Operations in Shell

Create a new blog post:

python
from myapp.models import BlogPost BlogPost.objects.create(title="Shell Blog", content="Created from Django shell", author="Neelamohan")

Fetch all records:

python
BlogPost.objects.all()

Filter records:

python
BlogPost.objects.filter(author="Neelamohan")

✅ Hands-on: Create a Database Model for a Blog App and Perform CRUD Operations

Step 1: Define the BlogPost Model (models.py)

python
from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() author = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title

Step 2: Run Migrations

bash
python manage.py makemigrations python manage.py migrate

Step 3: Register the Model in admin.py

python
from django.contrib import admin from .models import BlogPost admin.site.register(BlogPost)

Step 4: Perform CRUD Operations in Django Shell

bash
python manage.py shell

python
# Create a new blog post from myapp.models import BlogPost new_post = BlogPost.objects.create(title="My Blog", content="This is my first blog post.", author="Neelamohan") # Retrieve all posts BlogPost.objects.all() # Update a blog post post = BlogPost.objects.get(id=1) post.title = "Updated Title" post.save() # Delete a post post.delete()

📌 Module 4: Django Views & Templates

In this module, you'll learn about Django Views, Template Language, Static Files, and Template Inheritance to build dynamic web pages.


🔹 Understanding Views and Function-Based Views (FBV)

What is a View in Django?

A view in Django is a function or class that takes an HTTP request and returns a response.

Django supports two types of views:
1️⃣ Function-Based Views (FBV) - Uses simple functions.
2️⃣ Class-Based Views (CBV) - Uses classes for complex views (covered later).


Creating a Function-Based View (FBV)

Step 1: Define a View in views.py

Open views.py inside your Django app (myapp/views.py):

python
from django.http import HttpResponse from django.shortcuts import render def home(request): return HttpResponse("Hello, Welcome to My Django Website!")

Step 2: Map the View to a URL in urls.py

Modify your app's urls.py (myapp/urls.py):

python
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]

Now, when you visit http://127.0.0.1:8000/, it will display:
📌 "Hello, Welcome to My Django Website!"


🔹 Using Django Template Language

Django provides a Template Language for writing dynamic HTML.

Common Template Tags:

1️⃣ Loops ({% for %})

html
{% for item in items %} <p>{{ item }}</p> {% endfor %}

2️⃣ Conditions ({% if %})

html
{% if user.is_authenticated %} <p>Welcome, {{ user.username }}!</p> {% else %} <p>Please log in.</p> {% endif %}

3️⃣ Include Other Templates

html
{% include 'header.html' %}

4️⃣ Filters ({{ variable|filter }})

html
<p>{{ username|upper }}</p> <!-- Converts username to uppercase -->

🔹 Rendering Templates in Views

Instead of returning plain text (HttpResponse), let's render an HTML template.

Step 1: Create a Template File (home.html)

Inside your Django app, create a folder templates/myapp/ and add home.html:

📂 myapp/templates/myapp/home.html

html
<!DOCTYPE html> <html> <head> <title>My Django Website</title> </head> <body> <h1>Welcome to My Website</h1> <p>Hello, {{ name }}!</p> </body> </html>

Step 2: Modify the View to Use a Template (views.py)

python
from django.shortcuts import render def home(request): context = {"name": "Neelamohan"} return render(request, "myapp/home.html", context)

Now, when you visit http://127.0.0.1:8000/, it will display:
📌 "Hello, Neelamohan!"


🔹 Handling Static Files (CSS, JS, Images)

Step 1: Create a static Folder

Inside your Django app, create a static folder for CSS, JS, and images.

📂 myapp/static/css/style.css

css
body { background-color: #f4f4f4; font-family: Arial, sans-serif; }

📂 myapp/static/images/logo.png

Step 2: Load Static Files in Templates (home.html)

html
{% load static %} <!DOCTYPE html> <html> <head> <title>My Django Website</title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> </head> <body> <h1>Welcome to My Website</h1> <img src="{% static 'images/logo.png' %}" alt="Logo"> </body> </html>

🔹 Template Inheritance in Django

Instead of writing the same code in multiple files, Django supports template inheritance.

Step 1: Create a Base Template (base.html)

📂 myapp/templates/myapp/base.html

html
<!DOCTYPE html> <html> <head> <title>{% block title %}My Django Website{% endblock %}</title> </head> <body> <header> <h1>My Website Header</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>Copyright © 2025</p> </footer> </body> </html>

Step 2: Extend the Base Template in home.html

📂 myapp/templates/myapp/home.html

html
{% extends 'myapp/base.html' %} {% block title %}Home Page{% endblock %} {% block content %} <h2>Welcome to My Website</h2> <p>Hello, {{ name }}!</p> {% endblock %}

Now, home.html will automatically inherit the structure of base.html.


✅ Hands-on: Create a Dynamic Home Page using Django Templates

Step 1: Define the View in views.py

python
from django.shortcuts import render def home(request): context = {"name": "Neelamohan"} return render(request, "myapp/home.html", context)

Step 2: Create a Base Template (base.html)

html
<!DOCTYPE html> <html> <head> <title>{% block title %}My Django Website{% endblock %}</title> </head> <body> <header> <h1>My Website Header</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>Copyright © 2025</p> </footer> </body> </html>

Step 3: Create the Home Page Template (home.html)

html
{% extends 'myapp/base.html' %} {% block title %}Home Page{% endblock %} {% block content %} <h2>Welcome to My Website</h2> <p>Hello, {{ name }}!</p> {% endblock %}

Step 4: Modify urls.py to Map the View

python
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]

📌 Module 5: Django Forms & User Input Handling

This module covers HTML forms in Django, how to handle GET and POST requests, how to use Django ModelForms, and how to validate user input.


🔹 Creating HTML Forms in Django

Forms allow users to enter data, such as login credentials, feedback, or messages.

Basic HTML Form in Django

To create a simple form in Django, use the following steps:

Step 1: Create a Template (form.html)

📂 myapp/templates/myapp/form.html

html
<!DOCTYPE html> <html> <head> <title>Simple Form</title> </head> <body> <h2>Enter Your Name</h2> <form action="" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Enter your name"> <button type="submit">Submit</button> </form> </body> </html>

🔹 Handling Form Submissions (GET & POST)

Step 1: Create a View to Handle Form Submission

Edit views.py:

python
from django.shortcuts import render def simple_form(request): if request.method == "POST": username = request.POST.get("username") return render(request, "myapp/form.html", {"message": f"Hello, {username}!"}) return render(request, "myapp/form.html")

Step 2: Add URL Pattern for the Form in urls.py

python
from django.urls import path from . import views urlpatterns = [ path('form/', views.simple_form, name='simple_form'), ]

Now, when a user enters a name and clicks "Submit," it will display:
📌 "Hello, [User's Name]!"


🔹 Django ModelForms for Automatic Form Handling

Instead of manually handling form fields, Django provides ModelForms, which automatically create forms based on models.

Step 1: Create a Model (models.py)

python
from django.db import models class Contact(models.Model): name = models.CharField(max_length=100) email = models.EmailField() message = models.TextField() def __str__(self): return self.name

Run the migrations:

bash
python manage.py makemigrations python manage.py migrate

Step 2: Create a ModelForm (forms.py)

Create a forms.py file inside myapp/ and add the following code:

python
from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'message']

Step 3: Create a View to Handle the Form (views.py)

python
from django.shortcuts import render from .forms import ContactForm def contact_view(request): form = ContactForm() if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() return render(request, "myapp/contact.html", {"message": "Form submitted successfully!"}) return render(request, "myapp/contact.html", {"form": form})

Step 4: Create a Template (contact.html)

📂 myapp/templates/myapp/contact.html

html
<!DOCTYPE html> <html> <head> <title>Contact Form</title> </head> <body> <h2>Contact Us</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% if message %} <p style="color: green;">{{ message }}</p> {% endif %} </body> </html>

Step 5: Add URL Pattern in urls.py

python
urlpatterns = [ path('contact/', views.contact_view, name='contact'), ]

Now, visiting http://127.0.0.1:8000/contact/ will show a Contact Form that saves data to the database.


🔹 Validating User Inputs

Django provides built-in validation methods.

Add Validation in forms.py

Modify the ContactForm class:

python
class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'message'] def clean_name(self): name = self.cleaned_data.get("name") if len(name) < 3: raise forms.ValidationError("Name must be at least 3 characters long.") return name def clean_email(self): email = self.cleaned_data.get("email") if not email.endswith("@gmail.com"): raise forms.ValidationError("Only Gmail accounts are allowed.") return email

Now, if a user enters an invalid name or non-Gmail email, they will see an error message.


✅ Hands-on: Create a Contact Form with Input Validation

Steps to Implement a Contact Form with Validation

1️⃣ Create a Contact model in models.py
2️⃣ Create a ContactForm in forms.py
3️⃣ Add validation in forms.py
4️⃣ Create a contact_view in views.py
5️⃣ Create a contact.html template
6️⃣ Add the URL pattern in urls.py

Now, test the form by submitting valid and invalid inputs.

📌 Module 6: Django Authentication & User Management

This module covers user authentication, including registration, login, password reset, and user permissions. You’ll also build a User Login & Signup System using Django’s built-in authentication.


🔹 User Registration & Login System

Step 1: Configure Django’s Authentication System

Django comes with a built-in authentication system.
Ensure INSTALLED_APPS in settings.py contains:

python
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # Required for authentication 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # Your app name ]

Step 2: Create a User Registration Form (forms.py)

📂 myapp/forms.py

python
from django import forms from django.contrib.auth.models import User class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] def clean(self): cleaned_data = super().clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password and confirm_password and password != confirm_password: raise forms.ValidationError("Passwords do not match!")

Step 3: Create User Registration View (views.py)

📂 myapp/views.py

python
from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from .forms import RegisterForm def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password'] ) user.save() return redirect('login') # Redirect to login page after registration else: form = RegisterForm() return render(request, 'myapp/register.html', {'form': form})

Step 4: Create the Registration Template (register.html)

📂 myapp/templates/myapp/register.html

html
<!DOCTYPE html> <html> <head> <title>Register</title> </head> <body> <h2>User Registration</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form> </body> </html>

Step 5: Add User Registration URL (urls.py)

📂 myapp/urls.py

python
from django.urls import path from . import views urlpatterns = [ path('register/', views.register, name='register'), ]

🔹 User Login System

Step 1: Create Login View (views.py)

python
from django.contrib.auth import authenticate, login def user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') # Redirect to home after login else: return render(request, 'myapp/login.html', {'error': "Invalid credentials!"}) return render(request, 'myapp/login.html')

Step 2: Create Login Template (login.html)

html
<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>User Login</h2> {% if error %} <p style="color: red;">{{ error }}</p> {% endif %} <form method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Login</button> </form> </body> </html>

Step 3: Add Login URL (urls.py)

python
urlpatterns += [ path('login/', views.user_login, name='login'), ]

🔹 Password Reset & Change Password

Django provides built-in password reset functionality.

Step 1: Add Password Reset URLs (urls.py)

python
from django.contrib.auth import views as auth_views urlpatterns += [ path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ]

Step 2: Enable Email Backend for Reset

In settings.py, configure email:

python
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

This will print the reset link in the console.


🔹 Authentication with Django's Built-in User Model

Django provides the User model to manage authentication.
To get user details, use:

python
from django.contrib.auth.models import User user = User.objects.get(username='neelamohan') print(user.email)

🔹 Using Middleware for Authentication

Middleware can restrict access to authenticated users.

Modify views.py:

python
from django.contrib.auth.decorators import login_required @login_required def dashboard(request): return render(request, 'myapp/dashboard.html')

Now, users must log in to access /dashboard/.


🔹 User Permissions and Groups

Django provides permission management.

Step 1: Assign a Permission

python
from django.contrib.auth.models import User, Permission user = User.objects.get(username='neelamohan') permission = Permission.objects.get(codename='add_post') # Example permission user.user_permissions.add(permission)

Step 2: Check Permissions

python
if user.has_perm('app_name.add_post'): print("User can add posts!")

✅ Hands-on: Build a User Login & Signup System

Steps to Implement a Full Authentication System

1️⃣ Create a User Registration System (RegisterForm)
2️⃣ Build a Login System (user_login function)
3️⃣ Implement Password Reset (auth_views.PasswordResetView)
4️⃣ Use Middleware to Restrict Access (@login_required)
5️⃣ Manage User Permissions & Groups

Now, test your app by registering, logging in, and resetting the password.


Comments

Popular posts from this blog

Decision Tree Algorithm

  Decision Tree Algorithm The ID3 (Iterative Dichotomiser 3) algorithm is a Decision Tree classification algorithm that selects attributes based on Information Gain (IG) to maximize data purity at each step. Step 1: Understanding the Key Concepts Before implementing ID3, let's understand the core concepts: 1. Entropy (H) Entropy measures the impurity or uncertainty in the dataset: If all samples belong to one class , entropy = 0 (pure dataset). If the dataset is evenly split between classes, entropy = 1 (most uncertain). Formula for Entropy: H ( S ) = − ∑ p i log ⁡ 2 ( p i ) H(S) = - \sum p_i \log_2(p_i) H ( S ) = − ∑ p i ​ lo g 2 ​ ( p i ​ ) Where: p i p_i p i ​ = Probability of class i i i in dataset S S S log ⁡ 2 \log_2 lo g 2 ​ = Logarithm base 2 2. Information Gain (IG) Information Gain tells us how much entropy is reduced after splitting the data using an attribute. Formula for Information Gain: I G ( S , A ) = H ( S ) − H ( S ∣ A ) IG(S,A) = H(S)...

OPRATING SYSTEM

 https://drive.google.com/drive/folders/1VAYZuJLVeDBUd1UM2C4nvJTysqB3fMmt 📌 Module 1: Operating System Fundamentals 1️⃣ Introduction to Operating System & Evolution What is an Operating System (OS)? An Operating System (OS) is system software that acts as an interface between hardware and users , managing system resources efficiently. Key Functions of an OS ✅ Process Management – Controls execution of programs ✅ Memory Management – Allocates memory to processes ✅ File System Management – Manages files and directories ✅ Device Management – Controls hardware devices ✅ Security & Access Control – Protects data and system resources 2️⃣ Evolution of Operating Systems Era OS Type Example Characteristics 1950s Batch OS IBM Mainframes Executes jobs sequentially 1960s Multiprogramming OS UNIX Runs multiple processes simultaneously 1970s Time-Sharing OS MULTICS CPU switches between multiple users 1980s Personal Computing OS MS-DOS, Mac OS Single-user OS for PCs 199...

sql

  📌 Module 1: Introduction to SQL 🔹 What is SQL? 🔹 Database vs. DBMS vs. RDBMS 🔹 Types of Databases (SQL vs. NoSQL) 🔹 Popular SQL Databases (MySQL, PostgreSQL, SQLite, Oracle, MS SQL Server) 🔹 Installing MySQL/PostgreSQL & Setting Up Database ✅ Hands-on: ✔️ Install MySQL/PostgreSQL & Set Up a Test Database 📌 Module 2: SQL Basics - Data Retrieval 🔹 Understanding Database Tables & Schemas 🔹 SELECT Statement – Retrieving Data 🔹 Using WHERE Clause for Filtering 🔹 ORDER BY for Sorting Results 🔹 Using LIMIT & OFFSET for Pagination ✅ Hands-on: ✔️ Retrieve Employee Details from a Database 📌 Module 3: SQL Functions & Aggregation 🔹 Built-in Functions ( COUNT() , SUM() , AVG() , MIN() , MAX() ) 🔹 Using GROUP BY for Aggregation 🔹 HAVING Clause for Filtering Groups 🔹 Using DISTINCT for Unique Values ✅ Hands-on: ✔️ Find Total Salary, Average Salary, and Count of Employees per Department 📌 Module 4: SQL Joins & Relationsh...