jQuery


Beginners To Experts


The site is under development.

Django Tutorial

1.1 What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.

# Django is installed via pip:
pip install django
1.2 Installing Django

Install Django using pip to start building web applications.

# Open terminal and run:
pip install django
# Verify installation
django-admin --version
1.3 Creating a Django Project

Create a new Django project to organize your web application.

# Create project named 'myproject'
django-admin startproject myproject
# Navigate into project folder
cd myproject
# Run development server
python manage.py runserver
1.4 Understanding Project Structure

Explore the files and folders Django creates for your project.

myproject/  # Root project folder
├── manage.py # Command-line utility
├── myproject/ # Project settings module
│ ├── __init__.py
│ ├── settings.py # Configuration
│ ├── urls.py # URL routing
│ └── wsgi.py # Deployment entry point
1.5 Creating a Django App

Apps are modular components within a Django project. Create your first app.

# Create app named 'blog'
python manage.py startapp blog
# Add 'blog' to INSTALLED_APPS in settings.py
1.6 Writing Your First View

Views handle the logic of your web pages and return responses.

# blog/views.py
from django.http import HttpResponse

def home(request):
return HttpResponse('Hello, Django!')
1.7 Configuring URLs

Map URLs to your views so users can access your pages.

# myproject/urls.py
from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home), # Root URL
]
1.8 Running the Development Server

Start Django’s built-in server to test your application locally.

# Run server
python manage.py runserver
# Visit http://127.0.0.1:8000/ in browser
# You should see 'Hello, Django!'
1.9 Using Templates

Templates separate HTML design from Python code for dynamic content.

# blog/views.py
from django.shortcuts import render

def home(request):
return render(request, 'home.html')

# Create templates/home.html
<h1>Welcome to Django!</h1>
1.10 Summary and Next Steps

You now have a basic Django project and app setup. Next, learn about models and databases to store data.

# Next steps:
# - Create models in blog/models.py
# - Run migrations
# - Use Django admin to manage data

2.1 What Are Models?

Models define the structure of your database tables using Python classes.

# blog/models.py
from django.db import models

class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
2.2 Applying Migrations

After creating models, Django needs to create database tables via migrations.

# Create migration files
python manage.py makemigrations
# Apply migrations to database
python manage.py migrate
2.3 Using Django Admin

Django comes with a powerful admin interface to manage data.

# blog/admin.py
from django.contrib import admin
from .models import Post

admin.site.register(Post)
2.4 Creating Superuser

To access admin, create a superuser account.

# Create superuser
python manage.py createsuperuser
# Follow prompts for username, email, password
2.5 Running Admin Interface

Access admin panel to add, edit, delete posts.

# Run server
python manage.py runserver
# Visit http://127.0.0.1:8000/admin/ and login
2.6 Querying the Database

Use Django ORM to query model data in Python code.

# In Django shell
python manage.py shell
>> from blog.models import Post
>> Post.objects.all()
2.7 Adding Data Programmatically

Create new records via code.

>> post = Post(title='First Post', content='Hello world!')
>> post.save()
2.8 Updating Records

Modify existing database entries.

>> post = Post.objects.get(id=1)
>> post.title = 'Updated Title'
>> post.save()
2.9 Deleting Records

Remove records from the database.

>> post = Post.objects.get(id=1)
>> post.delete()
2.10 Summary and Next Steps

Models connect your app to the database. Next, learn about views and templates to display this data.

3.1 What Are Views?

Views contain the logic for handling requests and returning responses.

# blog/views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
posts = Post.objects.all()
return render(request, 'post_list.html', {'posts': posts})
3.2 Creating Templates

Templates define how your HTML pages look, with dynamic content.

# Create templates/post_list.html
<!DOCTYPE html>
<html>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% empty %}
<li>No posts found.</li>
{% endfor %}
</ul>
</body>
</html>
3.3 Configuring URLs

Link URL patterns to views to serve pages.

# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
path('', views.post_list, name='post_list'),
]
3.4 Including App URLs

Add app URLs to project’s main URL config.

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
3.5 Using Template Tags

Django templates use tags to add logic and output.

{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
{% endfor %}
3.6 Passing Context to Templates

Views send data to templates via context dictionaries.

return render(request, 'template.html', {'key': value})
3.7 Static Files Setup

Serve CSS, JavaScript, and images using static files.

# settings.py
STATIC_URL = '/static/'

# In template:
<link rel=\"stylesheet\" href=\"{% static 'css/style.css' %}\">
3.8 Template Inheritance

Create base templates to avoid repetition.

# base.html
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>

# post_list.html
{% extends 'base.html' %}
{% block content %}
... your content ...
{% endblock %}
3.9 Debugging Templates

Use Django debug mode and error messages to fix issues.

# settings.py
DEBUG = True
# Check console errors and template syntax
3.10 Summary and Next Steps

Views and templates handle displaying dynamic content. Next, learn forms to interact with users.

4.1 Introduction to Forms

Forms allow users to send data to your website.

# forms.py
from django import forms

class PostForm(forms.Form):
title = forms.CharField(max_length=100)
content = forms.CharField(widget=forms.Textarea)
4.2 Creating Forms in Views

Display forms and handle submissions in views.

# views.py
from django.shortcuts import render
from .forms import PostForm

def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
# Process data
title = form.cleaned_data['title']
content = form.cleaned_data['content']
# Save to DB or do something
else:
form = PostForm()
return render(request, 'create_post.html', {'form': form})
4.3 Form Templates

Render forms in templates using built-in helpers.

# create_post.html
<form method=\"post\">
{% csrf_token %}
{{ form.as_p }}
<button type=\"submit\">Submit</button>
</form>
4.4 Handling Validation

Django automatically validates form data.

# form.is_valid() checks required fields and types
# Errors accessible in template as {{ form.errors }}
4.5 Model Forms

ModelForms simplify creating forms tied to models.

# forms.py
from django.forms import ModelForm
from .models import Post

class PostModelForm(ModelForm):
class Meta:
model = Post
fields = ['title', 'content']
4.6 Saving Model Forms

Save form data directly to the database.

# views.py
if request.method == 'POST':
form = PostModelForm(request.POST)
if form.is_valid():
form.save()
4.7 Displaying Errors

Show validation errors to users.

# In template
{{ form.non_field_errors }}
{{ form.field_name.errors }}
4.8 Redirect After Submit

Redirect to another page after successful form submission.

from django.shortcuts import redirect

return redirect('post_list')
4.9 File Uploads

Handle file uploads with forms.

# forms.py
file = forms.FileField()

# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
4.10 Summary and Next Steps

Forms allow user input handling. Next, learn user authentication and permissions.

5.1 Django Template Basics

Templates are used to generate HTML dynamically using placeholders and template tags.

{% raw %}<!-- blog/templates/post_list.html -->
<h1>Posts</h1>
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
{% endfor %}{% endraw %}
5.2 Template Tags and Filters

Use built-in tags like for, if, and filters like lower, date to manipulate data.

{% raw %}{% if user.is_authenticated %}
Hello, {{ user.username|lower }}!
{% else %}
Hello, Guest!
{% endif %}{% endraw %}
5.3 Template Inheritance

Create base templates and extend them for DRY code.

{% raw %}<!-- base.html -->
<html>
<head>
<title>My Site</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>

<!-- post_list.html -->
{% extends "base.html" %}
{% block content %}
<h1>Posts</h1>
{% endblock %}{% endraw %}
5.4 Static Files Setup

Serve CSS, JS, and images using the staticfiles app.

# settings.py
STATIC_URL = '/static/'

# In templates
{% raw %}<link href="{% static 'css/style.css' %}" rel="stylesheet">{% endraw %}
5.5 Using the Static Template Tag

Load static files in templates.

{% raw %}{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">{% endraw %}
5.6 Organizing Static Files

Place static files in app-level or project-level static directories.

5.7 Collecting Static Files for Production

Use collectstatic to gather all static files in one place for deployment.

python manage.py collectstatic
5.8 Custom Template Filters

Create custom filters to transform data in templates.

# templatetags/custom_filters.py
from django import template

register = template.Library()

@register.filter
def cut(value, arg):
return value.replace(arg, '')
5.9 Template Context

Pass variables from views to templates.

def post_list(request):
posts = Post.objects.all()
return render(request, 'post_list.html', {'posts': posts})
5.10 Summary

Django templates separate logic and presentation, making your code cleaner and easier to maintain.

6.1 Model Relationships

Define relationships using ForeignKey, ManyToManyField, and OneToOneField.

from django.db import models

class Author(models.Model):
name = models.CharField(max_length=100)

class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
6.2 Model Methods

Add methods to your models to add functionality.

class Post(models.Model):
title = models.CharField(max_length=100)

def summary(self):
return self.title[:50]
6.3 Model Meta Options

Customize model behavior with the Meta class.

class Post(models.Model):
title = models.CharField(max_length=100)

class Meta:
ordering = ['title'] # Order by title alphabetically
6.4 QuerySet Filtering

Filter data with methods like filter(), exclude(), and get().

posts = Post.objects.filter(title__icontains='django')
6.5 Aggregation

Perform calculations on data like count, average, max, and min.

from django.db.models import Count
post_count = Post.objects.aggregate(Count('id'))
6.6 Related Object Access

Access related models via Django ORM.

author = Author.objects.get(id=1)
books = author.book_set.all()
6.7 Custom Managers

Create custom QuerySets for reusable queries.

class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
6.8 Signals

React to model events like save and delete.

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Post)
def notify_admin(sender, instance, created, **kwargs):
if created:
print('New post created:', instance.title)
6.9 Custom Fields

Create your own model field types.

from django.db import models
class PhoneNumberField(models.CharField):
pass # Custom validation can be added here
6.10 Summary

Advanced model concepts allow powerful data handling. Next, learn Django REST Framework for APIs.

7.1 What is Django REST Framework?

A toolkit to build Web APIs easily with Django.

# Install DRF
pip install djangorestframework
7.2 Adding REST Framework to Installed Apps

Add 'rest_framework' to settings.py

INSTALLED_APPS = [
...
'rest_framework',
]
7.3 Creating a Serializer

Serialize model instances to JSON and vice versa.

from rest_framework import serializers
from blog.models import Post

class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
7.4 Writing an API View

Create API views to handle requests.

from rest_framework.views import APIView
from rest_framework.response import Response
from blog.models import Post
from .serializers import PostSerializer

class PostList(APIView):
def get(self, request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)
7.5 Using Routers and ViewSets

Simplify routing with ViewSets and Routers.

from rest_framework import viewsets

class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
7.6 Registering Router URLs

Wire your API routes.

from rest_framework.routers import DefaultRouter
from .views import PostViewSet

router = DefaultRouter()
router.register(r'posts', PostViewSet)
7.7 API Authentication

Secure your APIs with token or session auth.

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
}
7.8 Testing APIs

Use tools like Postman or curl to test API endpoints.

curl http://127.0.0.1:8000/posts/
7.9 Pagination

Handle large result sets by paginating API responses.

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
7.10 Summary

DRF enables API building. Next, learn testing and deployment.

8.1 Why Testing Matters

Testing ensures your app works as expected and prevents bugs.

8.2 Writing Unit Tests

Create test cases for individual functions or methods.

from django.test import TestCase
from blog.models import Post

class PostModelTest(TestCase):
def test_str(self):
post = Post(title='Test Post')
self.assertEqual(str(post), 'Test Post')
8.3 Testing Views

Test views to ensure correct response and templates.

from django.urls import reverse

response = self.client.get(reverse('post_list'))
self.assertEqual(response.status_code, 200)
8.4 Using Fixtures

Preload test data using fixtures.

# Create fixture JSON
python manage.py dumpdata blog.Post --indent 2 > posts.json
# Load fixture in tests
fixtures = ['posts.json']
8.5 Integration Tests

Test multiple components together.

8.6 Using Selenium for Functional Tests

Automate browser testing for UI interactions.

# Install selenium
pip install selenium
8.7 Continuous Integration

Automate tests with CI tools like GitHub Actions.

8.8 Mocking External Services

Use mocking to isolate tests from third-party APIs.

8.9 Coverage Reports

Measure how much of your code is tested.

pip install coverage
coverage run manage.py test
coverage report
8.10 Summary

Testing improves code quality and reliability.

9.1 Preparing for Deployment

Collect static files and configure settings for production.

python manage.py collectstatic
9.2 Setting DEBUG=False

Turn off debug mode in production for security.

# settings.py
DEBUG = False
9.3 Using a Production-Ready Server

Use WSGI servers like Gunicorn or uWSGI.

pip install gunicorn
gunicorn myproject.wsgi
9.4 Configuring Database for Production

Use production-grade databases like PostgreSQL.

# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '',
}
}
9.5 Configuring Allowed Hosts

Set the domains your app can serve.

# settings.py
ALLOWED_HOSTS = ['yourdomain.com']
9.6 Setting Up HTTPS

Use SSL certificates to secure traffic.

9.7 Using Environment Variables

Keep secrets out of source code with env vars.

9.8 Monitoring and Logging

Track errors and performance using tools like Sentry.

9.9 Scaling Your Application

Use load balancers and caching for performance.

9.10 Summary

Deployment requires careful configuration for security and performance.

10.1 Middleware

Middleware processes requests/responses globally.

# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
...
]
10.2 Custom Middleware

Create middleware for custom processing.

class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
print('Before view')
response = self.get_response(request)
print('After view')
return response
10.3 Signals

Hook into Django’s signal system for event handling.

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def user_saved(sender, instance, created, **kwargs):
if created:
print('New user created:', instance.username)
10.4 Caching

Improve performance with caching.

# settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
10.5 Custom Template Tags

Create custom tags to extend templates.

# templatetags/my_tags.py
from django import template

register = template.Library()

@register.simple_tag
def greet(name):
return f'Hello, {name}!'
10.6 Asynchronous Views

Use async views for better performance on I/O bound tasks.

from django.http import JsonResponse
import asyncio

async def async_view(request):
await asyncio.sleep(1)
return JsonResponse({'message': 'Async response'})
10.7 File Handling

Manage file uploads and serve files.

# models.py
file = models.FileField(upload_to='uploads/')
10.8 Custom User Model

Create a custom user model for flexibility.

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
pass
10.9 Signals in Depth

Use signals for decoupled app interactions.

10.10 Summary

Advanced features let you customize Django to your needs.

11.1 Introduction to Forms

Django forms simplify HTML form handling and validation.

from django import forms

class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
11.2 ModelForms

Create forms directly from models for easier CRUD operations.

from django.forms import ModelForm
from blog.models import Post

class PostForm(ModelForm):
class Meta:
model = Post
fields = ['title', 'content']
11.3 Form Validation

Customize validation by overriding clean() methods.

def clean_email(self):
email = self.cleaned_data.get('email')
if not email.endswith('@example.com'):
raise forms.ValidationError("Invalid domain")
return email
11.4 Handling Form Submission

Process form data in views.

def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# process form.cleaned_data
pass
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
11.5 Displaying Errors

Show form validation errors in templates.

{% raw %}{{ form.non_field_errors }}
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}{% endraw %}
11.6 Custom Widgets

Customize input elements for better UI.

class PostForm(ModelForm):
class Meta:
model = Post
widgets = {
'content': forms.Textarea(attrs={'rows':4, 'cols':15}),
}
11.7 Formsets

Manage multiple forms on a single page.

from django.forms import formset_factory
ContactFormSet = formset_factory(ContactForm, extra=3)
11.8 CSRF Protection

Use CSRF tokens to protect against attacks.

{% raw %}<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>{% endraw %}
11.9 File Uploads in Forms

Handle file uploads with forms and models.

file = forms.FileField()

# In view handle request.FILES
form = UploadForm(request.POST, request.FILES)
11.10 Summary

Forms handle user input and validation with ease.

12.1 Built-in User Model

Django provides a default User model for authentication.

from django.contrib.auth.models import User
user = User.objects.create_user('john', 'john@example.com', 'password123')
12.2 User Registration

Create views and forms to register users.

from django.contrib.auth.forms import UserCreationForm
form = UserCreationForm()
12.3 Login and Logout

Use built-in views for user login and logout.

from django.contrib.auth import login, logout, authenticate

user = authenticate(username='john', password='password123')
if user is not None:
login(request, user)
12.4 Password Management

Reset and change passwords securely.

from django.contrib.auth.forms import PasswordChangeForm
form = PasswordChangeForm(user=request.user)
12.5 Permissions and Groups

Assign permissions and groups for access control.

from django.contrib.auth.models import Group, Permission
group = Group.objects.create(name='Editors')
12.6 Custom User Model

Customize User model for extra fields.

from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
phone = models.CharField(max_length=15, blank=True)
12.7 Authentication Backends

Customize how users are authenticated.

12.8 User Profile

Extend user info with a profile model.

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank=True)
12.9 Middleware for Authentication

Django middleware handles sessions and user authentication automatically.

12.10 Summary

Django’s authentication framework is robust and extensible.

13.1 What is Middleware?

Middleware processes requests and responses globally in Django.

13.2 Built-in Middleware Examples

Django provides security, session, authentication, and other middleware.

13.3 Writing Custom Middleware

Define a middleware class to customize request/response processing.

class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
# Code executed before view
response = self.get_response(request)
# Code executed after view
return response
13.4 Middleware Ordering

Order in settings.py matters, middleware runs top-down on request and bottom-up on response.

13.5 Using Middleware to Add Headers
def __call__(self, request):
response = self.get_response(request)
response['X-Custom-Header'] = 'Value'
return response
13.6 Exception Handling in Middleware

Catch exceptions and provide custom error pages.

13.7 Middleware and Authentication

Authentication middleware attaches the user to request objects.

13.8 Performance Considerations

Keep middleware efficient to avoid slowing down requests.

13.9 Third-party Middleware

Use middleware from libraries for features like CORS, compression.

13.10 Summary

Middleware is powerful for global request/response processing.

14.1 What are Signals?

Signals allow decoupled apps to get notified about events.

14.2 Built-in Signals

Common signals include pre_save, post_save, pre_delete, post_delete.

14.3 Creating Signal Handlers
from django.db.models.signals import post_save
from django.dispatch import receiver
from blog.models import Post

@receiver(post_save, sender=Post)
def notify_on_post_save(sender, instance, created, **kwargs):
if created:
print(f'New post created: {instance.title}')
14.4 Connecting Signals

Connect signals using decorators or connect() method.

14.5 Using Signals to Update Related Models

Automatically update or create related objects.

14.6 Signal Best Practices

Avoid heavy processing in signal handlers to keep app responsive.

14.7 Testing Signals

Test signal functionality with unit tests.

14.8 Disconnecting Signals

Remove signal handlers if needed to avoid side effects.

14.9 Custom Signals

Define your own signals for custom app logic.

14.10 Summary

Signals help keep apps modular and decoupled.

15.1 Why Cache?

Speed up your site by caching expensive computations and queries.

15.2 Configuring Cache Backends
# settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
15.3 Using Cache API
from django.core.cache import cache
cache.set('my_key', 'hello', 30) # cache for 30 seconds
value = cache.get('my_key')
15.4 Template Fragment Caching

Cache parts of templates.

{% raw %}{% load cache %}
{% cache 600 sidebar %}
...sidebar content...
{% endcache %}{% endraw %}
15.5 View Caching

Cache entire views for performance.

from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def my_view(request):
...
15.6 Low-Level Cache API

Cache anything with custom keys.

15.7 Cache Invalidation

Plan when to clear or update cache entries.

15.8 Using Redis or Memcached

Use external cache backends for production.

15.9 Cache and Sessions

Cache session data for faster access.

15.10 Summary

Caching is vital for scaling Django apps.

16.1 Recap of Signals

Review how signals help with decoupled communication.

16.2 Common Use Cases

Examples: sending notifications, updating caches, logging.

16.3 Post Save Signal Example
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
16.4 Post Delete Signal Example
@receiver(post_delete, sender=Post)
def log_deletion(sender, instance, **kwargs):
print(f"Post deleted: {instance.title}")
16.5 Using Signals to Update Cache

Clear or refresh cache when data changes.

16.6 Signal Handler Performance

Keep handlers fast and non-blocking.

16.7 Testing Signals

Write tests that ensure signals fire correctly.

16.8 Debugging Signals

Use logging or breakpoints to debug signal handlers.

16.9 Alternatives to Signals

Consider explicit calls or messaging queues for complex workflows.

16.10 Summary

Signals are useful but require care for maintainability.

17.1 Authentication Overview

Secure your APIs with authentication mechanisms.

17.2 Session Authentication

Uses Django’s session framework.

17.3 Token Authentication

Simple token-based authentication.

from rest_framework.authtoken.models import Token
token = Token.objects.create(user=user)
17.4 JWT Authentication

Use JSON Web Tokens for stateless auth.

17.5 OAuth2 Authentication

Third-party OAuth2 providers integration.

17.6 Custom Authentication

Implement your own authentication class.

17.7 Permission Classes

Define who can access what in your API.

17.8 Throttling

Limit request rates to prevent abuse.

17.9 Testing Authentication

Write tests to verify auth functionality.

17.10 Summary

Proper authentication is critical for API security.

18.1 What are Serializers?

Convert complex data types to JSON and back.

18.2 Serializer Classes
from rest_framework import serializers

class PostSerializer(serializers.Serializer):
title = serializers.CharField(max_length=100)
content = serializers.CharField()
18.3 ModelSerializer

Serializer tied directly to models.

class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'content']
18.4 Validation in Serializers

Use validate_fieldname or validate() methods.

18.5 Nested Serializers

Serialize related objects inside main serializers.

18.6 Serializer Methods

Add custom read-only fields with get_().

18.7 Serializer Relations

Use PrimaryKeyRelatedField or StringRelatedField.

18.8 Performance Considerations

Optimize serialization for large datasets.

18.9 Testing Serializers

Write tests to validate serializer behavior.

18.10 Summary

Serializers are essential for API data exchange.

19.1 What are Viewsets?

Viewsets combine logic for multiple views in a single class.

19.2 Router Basics

Automatically generate URL conf for viewsets.

from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'posts', PostViewSet)
19.3 ModelViewSet

CRUD operations in one class.

19.4 Custom Actions

Add extra actions using @action decorator.

19.5 Nested Routers

Handle nested resource routing.

19.6 Pagination

Paginate large querysets in APIs.

19.7 Filtering & Searching

Allow filtering and searching on endpoints.

19.8 Throttling

Limit API request rates per user.

19.9 Permissions

Secure your API endpoints.

19.10 Summary

Viewsets and routers simplify API design.

20.1 QuerySet Basics

QuerySets represent collections of objects from the database.

Post.objects.all()
20.2 Filtering QuerySets
Post.objects.filter(author='john')
20.3 Chaining QuerySets
Post.objects.filter(published=True).exclude(title__icontains='draft')
20.4 Aggregation

Calculate sums, averages, counts.

from django.db.models import Count
Post.objects.aggregate(total=Count('id'))
20.5 Annotate

Add calculated fields to QuerySets.

from django.db.models import Count
Post.objects.annotate(comment_count=Count('comments'))
20.6 Select Related

Optimize queries by joining related tables.

Post.objects.select_related('author')
20.7 Prefetch Related

Fetch many-to-many and reverse foreign keys efficiently.

Post.objects.prefetch_related('tags')
20.8 Raw SQL Queries

Execute raw SQL when needed.

Post.objects.raw('SELECT * FROM blog_post WHERE published = %s', [True])
20.9 Custom Managers

Extend QuerySets with custom methods.

class PostManager(models.Manager):
def published(self):
return self.filter(published=True)
20.10 Summary

Mastering QuerySets improves app performance and flexibility.

21.1 Overview of Signals

Signals allow decoupled apps to react to certain actions in Django.

21.2 Post Save Signal with Conditions

Trigger actions only on specific field changes.

from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import Profile

@receiver(post_save, sender=Profile)
def profile_updated(sender, instance, created, **kwargs):
if not created and instance.status == 'active':
print('Profile activated!')
21.3 Using pre_save to Modify Data

Change model data before saving.

from django.db.models.signals import pre_save
@receiver(pre_save, sender=Profile)
def modify_profile(sender, instance, **kwargs):
instance.name = instance.name.title()
21.4 Signal Chaining

Multiple signals can be triggered for one event.

21.5 Disconnecting Signals

Temporarily disconnect signals to avoid side effects during tests.

post_save.disconnect(receiver=profile_updated, sender=Profile)
21.6 Custom Signal Creation

Create your own signal for app-specific events.

from django.dispatch import Signal
order_completed = Signal(providing_args=["order_id"])
21.7 Sending Custom Signals
order_completed.send(sender=self.__class__, order_id=order.id)
21.8 Use Cases for Signals

Logging, notifications, cache updates, etc.

21.9 Pitfalls

Avoid heavy processing and circular signals.

21.10 Summary

Signals help keep code modular but require careful use.

22.1 Why Test?

Ensure code correctness and prevent regressions.

22.2 Writing Your First Test
from django.test import TestCase
from myapp.models import Post

class PostModelTest(TestCase):
def test_str_method(self):
post = Post(title='Test')
self.assertEqual(str(post), 'Test')
22.3 Testing Views

Test response status and templates used.

def test_homepage(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'home.html')
22.4 Testing Forms
def test_form_valid(self):
data = {'name': 'John', 'email': 'john@example.com'}
form = ContactForm(data=data)
self.assertTrue(form.is_valid())
22.5 Fixtures

Preload test data using fixtures or setUp methods.

22.6 setUp and tearDown

Prepare and clean up test environment.

def setUp(self):
self.user = User.objects.create_user('testuser')
22.7 Testing Models with Database

Use Django's test database for isolated tests.

22.8 Running Tests
python manage.py test
22.9 Continuous Integration

Integrate tests into your CI pipeline for automation.

22.10 Summary

Testing improves reliability and maintainability.

23.1 Complex Filters
from django.db.models import Q
Post.objects.filter(Q(title__icontains='django') | Q(content__icontains='framework'))
23.2 F Expressions

Perform database operations without fetching objects.

from django.db.models import F
Post.objects.update(views=F('views') + 1)
23.3 Subqueries

Use subqueries to filter or annotate.

23.4 Exists Queries
from django.db.models import Exists, OuterRef
comments = Comment.objects.filter(post=OuterRef('pk'))
Post.objects.annotate(has_comments=Exists(comments))
23.5 Aggregates

Count, Sum, Avg, Max, Min.

23.6 Window Functions

Advanced SQL window functions for ranking, running totals.

23.7 Raw SQL Queries

Use raw() for complex queries not supported by ORM.

23.8 QuerySet Performance Tips

Use select_related, prefetch_related to reduce DB hits.

23.9 Custom QuerySets

Add reusable filters or methods.

23.10 Summary

Master advanced querying for efficient apps.

24.1 Why Pagination?

Break large querysets into manageable pages.

24.2 PageNumberPagination

Basic page number based pagination.

from rest_framework.pagination import PageNumberPagination
class MyPagination(PageNumberPagination):
page_size = 10
24.3 LimitOffsetPagination

Supports limit and offset parameters.

24.4 CursorPagination

Use cursor-based pagination for large datasets.

24.5 Adding Pagination to Views
from rest_framework import viewsets
class PostViewSet(viewsets.ModelViewSet):
pagination_class = MyPagination
queryset = Post.objects.all()
serializer_class = PostSerializer
24.6 Custom Pagination Responses

Customize the pagination response format.

24.7 Pagination and Filtering

Combine pagination with filters and searches.

24.8 Performance Considerations

Pagination improves response time and reduces memory.

24.9 Testing Pagination

Write tests to verify page sizes and content.

24.10 Summary

Pagination is essential for scalable APIs.

25.1 Template Inheritance

Use base templates and extend them.

{% raw %}<!-- base.html -->
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>

<!-- child.html -->
{% extends "base.html" %}
{% block content %}Hello world{% endblock %}{% endraw %}
25.2 Template Tags

Use built-in and custom tags.

25.3 Template Filters

Modify variables with filters.

{% raw %}{{ name|lower }}{% endraw %}
25.4 Custom Template Tags and Filters

Create reusable logic in templates.

25.5 Inclusion Tags

Render a sub-template with its own context.

25.6 Using the With Tag
{% raw %}{% with total=business.employees.count %}Total Employees: {{ total }}{% endwith %}{% endraw %}
25.7 Conditional Logic
{% raw %}{% if user.is_authenticated %}Welcome!{% else %}Please login.{% endif %}{% endraw %}
25.8 Loops
{% raw %}{% for item in list %}{{ item }}{% endfor %}{% endraw %}
25.9 Template Debugging

Use Django debug toolbar or logging.

25.10 Summary

Master templates to build dynamic pages.

26.1 What is Django Channels?

Adds WebSocket and asynchronous support to Django.

26.2 Installing Channels
pip install channels
26.3 Configuring ASGI

Set ASGI application in settings.py.

ASGI_APPLICATION = 'myproject.asgi.application'
26.4 Writing Consumers

Consumers handle WebSocket connections.

from channels.generic.websocket import WebsocketConsumer
import json

class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def receive(self, text_data):
self.send(text_data=json.dumps({'message': text_data}))
26.5 Routing WebSockets
from django.urls import re_path
from .consumers import ChatConsumer

websocket_urlpatterns = [
re_path(r'ws/chat/$', ChatConsumer.as_asgi()),
]
26.6 Running Channels Server
daphne myproject.asgi:application
26.7 Group Communication

Send messages to groups of connections.

26.8 Integrating with Django ORM

Access database asynchronously in consumers.

26.9 Use Cases

Chat apps, live notifications, real-time dashboards.

26.10 Summary

Django Channels extends Django with async and real-time capabilities.

27.1 Choosing a Server

Choose a WSGI server to run your Django app in production. Gunicorn is popular for synchronous apps, uWSGI is flexible, and Daphne supports async features (ASGI).

# Run Gunicorn to serve your app on port 8000
gunicorn myproject.wsgi:application --bind 0.0.0.0:8000
27.2 Using a Reverse Proxy

Set up Nginx or Apache as a front-facing web server to handle SSL, serve static files, and proxy requests to Gunicorn/uWSGI.

# Nginx example config snippet
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /static/ {
        alias /path/to/staticfiles/;
    }
}
27.3 Managing Static and Media Files

Django collects static files from your apps into a single directory with collectstatic. Configure your web server to serve these efficiently. Media files (user uploads) should be served separately.

# Collect static files
python manage.py collectstatic

# In production, configure Nginx to serve /static/ and /media/ URLs directly.
27.4 Environment Variables

Use environment variables for sensitive data like SECRET_KEY, DB credentials, and debug flags. This avoids storing secrets in source code.

# Example using python-decouple in settings.py
from decouple import config

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
27.5 Database Configuration

Use production-ready databases like PostgreSQL, and secure connections with SSL where possible.

# settings.py PostgreSQL example
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'prod_db',
        'USER': 'dbuser',
        'PASSWORD': 'password',
        'HOST': 'dbserver.example.com',
        'PORT': '5432',
        'OPTIONS': {
            'sslmode': 'require',
        },
    }
}
27.6 HTTPS Setup

Encrypt communication by enabling HTTPS with SSL certificates (e.g., from Let's Encrypt).

# Nginx HTTPS config snippet
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
27.7 Monitoring and Logging

Set up logging to track errors and monitor app health using tools like Sentry or built-in logging.

# Basic Django logging setup in settings.py
LOGGING = {
    'version': 1,
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': '/var/log/django/error.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}
27.8 Performance Optimization

Optimize performance with caching, database indexing, and async views if appropriate.

# Cache a view for 15 minutes
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request):
    # expensive query or processing here
    ...
27.9 Scaling

Handle increased load by deploying multiple instances and using load balancers.

# Example HAProxy frontend config for load balancing multiple Gunicorn instances
frontend http-in
    bind *:80
    default_backend django_servers

backend django_servers
    server app1 192.168.1.10:8000 check
    server app2 192.168.1.11:8000 check
27.10 Summary

Following deployment best practices ensures your Django app runs securely, reliably, and efficiently in production.

28.1 Cross-Site Scripting (XSS)

Django templates auto-escape variables to prevent malicious scripts from executing.

{# Safe escaping example #}
{{ user_input }}  {# will be escaped automatically #}

{# To mark safe content deliberately use: #}
{{ safe_content|safe }}
28.2 Cross-Site Request Forgery (CSRF)

Django uses CSRF tokens to protect POST forms against cross-site request forgery.

{% raw %}
<form method="post"/>
    {% csrf_token %}
    <input type="text" name="name" />
    <button type="submit"/> Submit</button>

{% endraw %}
28.3 SQL Injection

Django ORM safely builds SQL queries to prevent injection attacks.

# Unsafe (do not use)
cursor.execute("SELECT * FROM users WHERE username = '%s'" % username)

# Safe (Django ORM)
User.objects.filter(username=username)
28.4 Clickjacking Protection

Use middleware to set X-Frame-Options headers to prevent your site from being embedded in iframes.

# settings.py
MIDDLEWARE = [
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # other middleware
]

X_FRAME_OPTIONS = 'DENY'  # or 'SAMEORIGIN'
28.5 Secure Password Storage

Django uses PBKDF2 with a salt for password hashing, protecting stored passwords.

# Create user securely
from django.contrib.auth.models import User

User.objects.create_user('username', password='securepassword')
28.6 HTTPS and Secure Cookies

Enable HTTPS and mark cookies as Secure and HttpOnly to protect them.

# settings.py
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
28.7 User Authentication Best Practices

Enforce strong passwords, session expiration, and limit login attempts.

# Using Django’s built-in validators
AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 8}},
    # more validators
]
28.8 Handling Sensitive Data

Encrypt sensitive data at rest and restrict access in your app and DB.

# Example: Encrypt field using django-encrypted-model-fields package
from encrypted_model_fields.fields import EncryptedCharField

class UserProfile(models.Model):
    ssn = EncryptedCharField(max_length=11)
28.9 Security Middleware

Enable Django’s security middleware for headers like Strict-Transport-Security, Content-Security-Policy, etc.

# settings.py
MIDDLEWARE += [
    'django.middleware.security.SecurityMiddleware',
]
SECURE_HSTS_SECONDS = 3600
SECURE_CONTENT_TYPE_NOSNIFF = True
28.10 Summary

Implementing these security best practices helps protect your Django app from common web vulnerabilities.

29.1 Why Cache?

Caching reduces database queries and speeds up page load by storing results temporarily.

29.2 Cache Backends

Django supports multiple cache backends: in-memory, file-based, Memcached, Redis.

29.3 Per-View Caching

Cache the entire output of a view function for a period of time.

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)  # cache for 15 minutes
def my_view(request):
    # Perform expensive computations or DB queries here
    ...
29.4 Template Fragment Caching

Cache only parts of a template (fragments) to optimize performance.

{% raw %}
{% cache 600 sidebar %}
    
{% endcache %}
{% endraw %}
29.5 Low-Level Cache API

Manually set, get, and delete cache keys in your code.

from django.core.cache import cache

cache.set('my_key', 'my_value', timeout=30)  # timeout in seconds
value = cache.get('my_key')
29.6 Cache Invalidation

Clear or update cache when the underlying data changes to prevent stale content.

# Example: clear cache when model saves
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=MyModel)
def clear_cache(sender, **kwargs):
    cache.delete('my_key')
29.7 Cache Key Design

Use descriptive and unique keys to avoid collisions in shared caches.

29.8 Distributed Caching

Use Redis or Memcached to share cache between multiple servers in a scalable setup.

29.9 Monitoring Cache Performance

Track cache hit/miss ratios and optimize accordingly.

29.10 Summary

Caching is essential to improve Django app performance and scalability.

30.1 What is Internationalization?

Internationalization (i18n) is preparing your app to support multiple languages and regional settings.

30.2 Enabling i18n in Settings

Set USE_I18N = True and configure available languages.

# settings.py
USE_I18N = True
LANGUAGES = [
    ('en', 'English'),
    ('fr', 'French'),
    ('es', 'Spanish'),
]
30.3 Marking Strings for Translation

Use Django's gettext function to mark strings for translation.

from django.utils.translation import gettext as _

message = _("Welcome to my site")
30.4 Creating Message Files

Generate message files for a language (e.g., French) with:

django-admin makemessages -l fr
30.5 Translating and Compiling

Translate the generated .po files, then compile with:

django-admin compilemessages
30.6 Using {% trans %} Template Tag

Translate strings in templates using the {% trans %} tag.

{% raw %}

{% trans "Hello World" %}

{% endraw %}
30.7 Locale Middleware

Add LocaleMiddleware to detect user's language preference automatically.

# settings.py
MIDDLEWARE = [
    'django.middleware.locale.LocaleMiddleware',
    # other middleware
]
30.8 Formatting Dates and Numbers

Use Django's localization filters in templates:

{% raw %}
{{ value|localize }}
{{ date_value|date:"SHORT_DATE_FORMAT" }}
{% endraw %}
30.9 Handling Time Zones

Enable timezone support and convert datetimes properly.

# settings.py
USE_TZ = True
TIME_ZONE = 'UTC'

# Convert datetime example
from django.utils import timezone

now = timezone.now()
30.10 Summary

Internationalization allows your Django app to reach a global audience by supporting multiple languages and locales.

31.1 Production Scheduling

Plans and optimizes manufacturing timelines and resources.

// Example: Job A before Job B to optimize time usage
if (jobA.finishTime <= jobB.startTime) {
    schedule(jobA);
    schedule(jobB);
}
31.2 Quality Control

Inspects products for defects and suggests corrections.

// Example: If defect detected in batch, notify technician
if (batch.hasDefect()) {
    notifyTechnician(batch.id);
}
31.3 Predictive Maintenance

Forecasts equipment failures before they occur.

// Example: If vibration exceeds threshold, predict fault
if (machine.vibration > threshold) {
    alert("Possible machine fault");
}
31.4 Inventory Monitoring

Keeps track of raw material usage.

// Example: Reorder if steel stock less than 10 tons
if (inventory.steel < 10) {
    reorder("steel");
}
31.5 Process Optimization

Improves efficiency by analyzing process steps.

// Example: Remove redundant process step C
if (process.hasRedundantStep("C")) {
    process.removeStep("C");
}
31.6 Energy Management

Minimizes energy consumption across machines.

// Example: Schedule heater to run at off-peak hours
if (currentTime.isOffPeak()) {
    heater.run();
}
31.7 Resource Allocation

Assigns workers and tools efficiently.

// Example: Assign worker A to station 3
assignWorker("WorkerA", "Station3");
31.8 Waste Reduction

Detects and reduces material waste in production.

// Example: Suggest trimming 2cm less to save material
if (wasteRate > acceptableLevel) {
    suggestTrimAdjustment(-2);
}
31.9 Safety Management

Flags unsafe conditions or processes.

// Example: Trigger alert if heat exceeds safe threshold
if (temperature > safeThreshold) {
    triggerAlert("Overheat detected");
}
31.10 Workflow Analysis

Analyzes process flow for delays or bottlenecks.

// Example: If step D delayed, increase staffing
if (stepD.delay > maxDelay) {
    increaseStaff("StepD");
}

32.1 Student Assessment

Evaluates student performance and recommends improvements.

// Example: Suggest practice if score below 60%
if (student.score < 60) {
    recommend("practice set");
}
32.2 Personalized Learning

Adapts lessons based on student learning pace.

// Example: Skip review for fast learners
if (student.learningSpeed == "fast") {
    skipLesson("review");
}
32.3 Career Guidance

Recommends careers based on interests and performance.

// Example: Suggest engineering for good math skills
if (student.skills.math > threshold) {
    recommendCareer("Engineering");
}
32.4 Content Recommendation

Suggests relevant materials and resources.

// Example: Recommend loop tutorials if learning Python
if (student.learningTopic == "Python") {
    recommendMaterial("loops tutorial");
}
32.5 Plagiarism Detection

Scans for copied content in assignments.

// Example: Flag assignment if similarity over 85%
if (assignment.similarityScore > 85) {
    flagAssignment(assignment.id);
}
32.6 Teacher Support

Helps educators with lesson planning and assessments.

// Example: Provide exercises on Algebra topic
if (lesson.topic == "Algebra") {
    provideExercises("Algebra");
}
32.7 Feedback Analysis

Processes student feedback to improve courses.

// Example: Suggest more interactive sessions if feedback low
if (feedback.interactivityScore < threshold) {
    suggestChange("more interactive sessions");
}
32.8 Attendance Monitoring

Tracks and analyzes student attendance patterns.

// Example: Send notification after 3 absences
if (student.absences >= 3) {
    sendNotification(student.id, "Attendance warning");
}
32.9 Curriculum Design

Recommends curriculum changes based on trends.

// Example: Add AI module to Computer Science course
if (industryTrend == "AI") {
    addCurriculumModule("CS", "AI");
}
32.10 Special Needs Support

Adapts content for students with disabilities.

// Example: Use audio resources for dyslexic students
if (student.hasDisability("dyslexia")) {
    useResource("audio");
}

33.1 Diagnosis Support

Assists doctors by suggesting possible diagnoses.

// Example: Suggest diagnosis if symptoms match
if (patient.symptoms.containsAll(["fever","cough"])) {
    suggestDiagnosis("flu");
}
33.2 Treatment Recommendations

Recommends treatments based on diagnosis.

// Example: Recommend antibiotics for bacterial infection
if (diagnosis == "bacterial infection") {
    recommendTreatment("antibiotics");
}
33.3 Drug Interaction Checking

Warns about dangerous drug combinations.

// Example: Alert if drugs A and B interact
if (patient.drugs.contains("DrugA") && patient.drugs.contains("DrugB")) {
    alert("Drug interaction warning");
}
33.4 Patient Monitoring

Tracks vital signs and alerts on abnormalities.

// Example: Alert if heart rate too high
if (patient.heartRate > 120) {
    sendAlert("High heart rate");
}
33.5 Medical Imaging Analysis

Analyzes images for abnormalities.

// Example: Flag tumor detected in X-ray image
if (imageAnalysis.detect("tumor")) {
    flagImage(patient.id, "tumor");
}
33.6 Appointment Scheduling

Optimizes doctor appointment times.

// Example: Schedule follow-up 2 weeks after treatment
scheduleAppointment(patient.id, treatmentDate.addWeeks(2));
33.7 Patient Record Management

Keeps and updates patient history.

// Example: Add new diagnosis to patient record
patient.record.addDiagnosis(diagnosis);
33.8 Health Risk Assessment

Assesses risk factors for diseases.

// Example: High risk if family history of diabetes
if (patient.familyHistory.contains("diabetes")) {
    markRisk(patient.id, "high");
}
33.9 Clinical Decision Support

Guides doctors through treatment protocols.

// Example: Follow protocol if patient has condition X
if (patient.condition == "X") {
    followProtocol("ProtocolX");
}
33.10 Summary

Expert systems improve healthcare decision-making.

34.1 Credit Scoring

Evaluates creditworthiness of applicants.

// Example: Approve loan if credit score above threshold
if (applicant.creditScore > 700) {
    approveLoan(applicant.id);
}
34.2 Fraud Detection

Detects suspicious transaction patterns.

// Example: Flag transaction if amount unusually high
if (transaction.amount > 10000) {
    flagTransaction(transaction.id);
}
34.3 Investment Recommendations

Suggests investment options based on risk profile.

// Example: Recommend bonds for low-risk investors
if (investor.riskProfile == "low") {
    recommendInvestment("bonds");
}
34.4 Loan Approval Automation

Automates loan processing decisions.

// Example: Auto-approve if income and credit good
if (applicant.income > 50000 && applicant.creditScore > 700) {
    autoApproveLoan(applicant.id);
}
34.5 Portfolio Management

Optimizes asset allocation for investors.

// Example: Rebalance portfolio monthly
if (today == portfolio.rebalanceDate) {
    rebalancePortfolio(investor.id);
}
34.6 Risk Assessment

Analyzes financial risks.

// Example: Flag high exposure to volatile stocks
if (portfolio.volatility > threshold) {
    alert("High risk exposure");
}
34.7 Compliance Checking

Ensures regulatory compliance.

// Example: Check transactions against compliance rules
if (!transaction.compliesWithRules()) {
    blockTransaction(transaction.id);
}
34.8 Tax Calculation

Calculates taxes automatically.

// Example: Calculate tax for given income
tax = calculateTax(income);
34.9 Customer Support Automation

Automates responses to common queries.

// Example: Auto-reply to FAQs
if (customer.query in faqList) {
    sendAutoReply(customer.id, faqList[query]);
}
34.10 Summary

Expert systems streamline financial operations and decision-making.

35.1 Automated FAQ Handling

Answers common questions automatically.

// Example: Return canned answer for known question
if (customer.question in faq) {
    answer = faq[customer.question];
}
35.2 Ticket Prioritization

Assigns priority to support tickets.

// Example: Mark ticket urgent if customer is VIP
if (ticket.customerStatus == "VIP") {
    ticket.priority = "High";
}
35.3 Chatbot Integration

Interacts with customers using AI chatbots.

// Example: Respond to greeting message
if (message == "hello") {
    respond("Hello! How can I help you?");
}
35.4 Sentiment Analysis

Analyzes customer sentiment to route requests.

// Example: Route angry messages to senior staff
if (sentiment == "angry") {
    routeTo("Senior Support");
}
35.5 Knowledge Base Management

Maintains and updates support articles.

// Example: Add new article when product updated
if (product.updated) {
    addKnowledgeBaseArticle("New features");
}
35.6 Escalation Management

Automates escalation processes.

// Example: Escalate ticket after 48 hours unresolved
if (ticket.age > 48 hours && !ticket.resolved) {
    escalate(ticket.id);
}
35.7 Feedback Collection

Collects customer feedback post-resolution.

// Example: Send survey after ticket closed
if (ticket.status == "Closed") {
    sendSurvey(ticket.customerId);
}
35.8 Multi-channel Support

Integrates support across email, chat, and phone.

// Example: Route query regardless of channel
routeQuery(query);
35.9 Analytics and Reporting

Generates reports on support metrics.

// Example: Report average resolution time weekly
generateReport("resolutionTime", "weekly");
35.10 Summary

Expert systems enhance customer support efficiency and quality.

36.1 Demand Forecasting

Predicts product demand to optimize stock levels.

// Example: Increase stock if demand predicted high
if (forecast.demand > stock.level) {
    orderMoreStock();
}
36.2 Supplier Selection

Chooses suppliers based on criteria like cost and quality.

// Example: Select supplier with best rating
supplier = selectSupplier(criteria = {rating: "high", cost: "low"});
36.3 Inventory Optimization

Keeps inventory at optimal levels to reduce costs.

// Example: Reduce inventory if turnover low
if (inventory.turnoverRate < threshold) {
    reduceInventory();
}
36.4 Logistics Planning

Plans transportation routes for efficiency.

// Example: Choose shortest delivery route
route = planRoute(deliveryPoints, optimize="distance");
36.5 Order Tracking

Monitors order status and updates customers.

// Example: Notify customer on shipment
if (order.status == "shipped") {
    notifyCustomer(order.id, "Your order has shipped");
}
36.6 Risk Management

Identifies risks in the supply chain.

// Example: Alert if supplier delayed
if (supplier.deliveryDelay > threshold) {
    alert("Supplier delay");
}
36.7 Cost Control

Monitors and reduces supply chain costs.

// Example: Suggest cheaper supplier options
if (currentSupplier.cost > budget) {
    suggestAlternativeSuppliers();
}
36.8 Compliance Monitoring

Ensures supply chain meets regulations.

// Example: Check supplier certifications
if (!supplier.isCertified()) {
    blockSupplier(supplier.id);
}
36.9 Sustainability Management

Monitors environmental impact of supply chain.

// Example: Prefer eco-friendly suppliers
if (supplier.ecoRating > threshold) {
    prioritizeSupplier(supplier.id);
}
36.10 Summary

Expert systems optimize supply chain efficiency and reduce risks.

37.1 Crop Monitoring

Monitors crop health using sensor data.

// Example: Alert if soil moisture too low
if (soil.moisture < threshold) {
    alert("Irrigation needed");
}
37.2 Pest Detection

Detects pest infestations early.

// Example: Detect pest presence from images
if (imageAnalysis.detect("pests")) {
    alert("Pest infestation detected");
}
37.3 Irrigation Management

Optimizes watering schedules.

// Example: Schedule irrigation based on moisture and weather
if (soil.moisture < threshold && !forecast.rain) {
    startIrrigation();
}
37.4 Fertilizer Application

Recommends fertilizer types and amounts.

// Example: Apply fertilizer if nitrogen low
if (soil.nitrogen < threshold) {
    applyFertilizer("Nitrogen", amount);
}
37.5 Harvest Timing

Suggests optimal harvest times for crops.

// Example: Harvest when crop moisture below target
if (crop.moisture < target) {
    suggestHarvest();
}
37.6 Weather Prediction

Uses weather data to aid farm decisions.

// Example: Alert frost risk in next 24 hours
if (weather.forecast("frost")) {
    alert("Frost warning");
}
37.7 Disease Management

Identifies crop diseases and suggests treatments.

// Example: Suggest treatment if blight detected
if (crop.hasDisease("blight")) {
    recommendTreatment("fungicide");
}
37.8 Equipment Management

Schedules maintenance for farm machinery.

// Example: Schedule tractor maintenance every 500 hours
if (equipment.hoursUsed > 500) {
    scheduleMaintenance("tractor");
}
37.9 Market Price Analysis

Analyzes commodity prices for selling decisions.

// Example: Suggest sell when price exceeds target
if (market.price > targetPrice) {
    suggestSell();
}
37.10 Summary

Expert systems enhance farm productivity and decision-making.

38.1 Route Optimization

Finds shortest or fastest routes.

// Example: Calculate route with minimal distance
route = calculateOptimalRoute(start, destination);
38.2 Traffic Management

Monitors and manages traffic flow.

// Example: Adjust traffic lights based on congestion
if (trafficDensity > threshold) {
    extendGreenLight();
}
38.3 Fleet Management

Tracks and schedules vehicles in a fleet.

// Example: Schedule maintenance for truck fleet
if (truck.hoursDriven > maintenanceInterval) {
    scheduleMaintenance(truck.id);
}
38.4 Accident Prediction

Identifies risky driving conditions.

// Example: Alert driver of slippery roads
if (weatherCondition == "rain" && roadCondition == "slippery") {
    alertDriver("Drive carefully");
}
38.5 Passenger Scheduling

Optimizes public transport timetables.

// Example: Increase buses during rush hours
if (timeOfDay == "rush hour") {
    increaseBusFrequency();
}
38.6 Vehicle Diagnostics

Monitors vehicle health and alerts on issues.

// Example: Alert if engine temperature too high
if (engine.temperature > safeLimit) {
    alert("Engine overheating");
}
38.7 Fuel Management

Optimizes fuel consumption.

// Example: Suggest route with best fuel efficiency
suggestRoute("fuel efficient");
38.8 Compliance Checking

Ensures vehicles meet legal requirements.

// Example: Check if driver hours comply with regulations
if (driver.hoursDriven > maxAllowed) {
    notifyComplianceIssue();
}
38.9 Incident Reporting

Automates accident and incident reports.

// Example: Generate report after accident detected
if (accidentDetected) {
    generateIncidentReport();
}
38.10 Summary

Expert systems improve safety and efficiency in transportation.

39.1 Document Review

Analyzes legal documents for issues.

// Example: Flag contracts missing clauses
if (!contract.hasClause("arbitration")) {
    flagDocument(contract.id);
}
39.2 Case Prediction

Predicts outcomes based on precedent.

// Example: Predict case win if similar precedent
if (case.similarTo(precedent) && precedent.outcome == "win") {
    predictOutcome("win");
}
39.3 Legal Research

Finds relevant laws and cases.

// Example: Search laws related to contract disputes
results = searchLegalDatabase("contract disputes");
39.4 Compliance Checking

Checks regulations adherence.

// Example: Verify company policies comply with regulations
if (!companyPolicies.complyWith(regulations)) {
    alertComplianceIssue();
}
39.5 Contract Drafting

Assists in creating legal contracts.

// Example: Suggest standard clauses for NDA
contract.addClauses(standardNDAClauses);
39.6 Litigation Support

Organizes evidence and case materials.

// Example: Categorize evidence by type
evidence.sortByType();
39.7 Client Consultation

Provides automated initial consultations.

// Example: Ask client basic questions to gather facts
askClient("Describe the issue");
39.8 Billing Automation

Automates invoicing and payment tracking.

// Example: Generate invoice after case closure
if (case.status == "closed") {
    generateInvoice(client.id);
}
39.9 Legal Analytics

Analyzes data for trends and risks.

// Example: Analyze frequency of contract disputes
analyzeTrend("contract disputes");
39.10 Summary

Expert systems assist in streamlining legal work and improving accuracy.

40.1 Recruitment Screening

Evaluates candidate resumes automatically.

// Example: Shortlist candidates with required skills
if (candidate.skills.containsAll(requiredSkills)) {
    shortlist(candidate.id);
}
40.2 Performance Evaluation

Analyzes employee performance metrics.

// Example: Flag employees with low productivity
if (employee.performanceScore < threshold) {
    flagEmployee(employee.id);
}
40.3 Training Recommendations

Suggests courses based on skill gaps.

// Example: Recommend course if skill below level
if (employee.skillLevel("Java") < desiredLevel) {
    recommendTraining("Java basics");
}
40.4 Attendance Monitoring

Tracks absenteeism and tardiness.

// Example: Alert if absences exceed limit
if (employee.absences > maxAllowed) {
    sendWarning(employee.id);
}
40.5 Employee Engagement

Monitors engagement via surveys.

// Example: Suggest team building if engagement low
if (survey.engagementScore < threshold) {
    suggestActivity("team building");
}
40.6 Payroll Management

Automates salary calculation and deductions.

// Example: Calculate payroll including overtime
payroll = calculateSalary(employee.hoursWorked, overtime);
40.7 Compliance and Legal

Ensures labor law compliance.

// Example: Check if working hours meet regulations
if (!employee.workingHours.compliesWithLaw()) {
    notifyHR(employee.id);
}
40.8 Succession Planning

Identifies candidates for key roles.

// Example: Mark potential successors for manager role
if (employee.potential > threshold) {
    addToSuccessionPlan(employee.id, "manager");
}
40.9 Conflict Resolution

Assists in resolving workplace conflicts.

// Example: Suggest mediation if conflict reported
if (conflict.reported) {
    suggestMediation(conflict.parties);
}
40.10 Summary

Expert systems streamline HR processes and improve employee management.

41.1 Customer Segmentation

Groups customers based on behavior and demographics.

// Example: Segment customers by purchase frequency
segments = segmentCustomers(customers, "purchaseFrequency");
41.2 Campaign Management

Plans and tracks marketing campaigns.

// Example: Launch campaign targeting segment A
launchCampaign("SegmentA");
41.3 Lead Scoring

Ranks potential customers based on interest.

// Example: Score leads based on website interactions
leads.forEach(lead => {
    lead.score = calculateLeadScore(lead);
});
41.4 Sentiment Analysis

Analyzes social media sentiment.

// Example: Analyze tweets mentioning brand
sentiment = analyzeSocialMedia("brandName");
41.5 Product Recommendation

Suggests products based on purchase history.

// Example: Recommend similar products
recommendations = recommendProducts(customer.purchaseHistory);
41.6 Pricing Optimization

Adjusts pricing based on market conditions.

// Example: Reduce price if sales drop
if (sales < target) {
    adjustPrice(product, -10);
}
41.7 Competitor Analysis

Tracks competitor activities.

// Example: Monitor competitor pricing
competitorPrice = getCompetitorPrice(product);
41.8 Market Trend Prediction

Forecasts market changes.

// Example: Predict rising demand for product category
if (trendAnalysis("category") == "rising") {
    increaseInventory("category");
}
41.9 Customer Feedback Analysis

Processes feedback to improve products.

// Example: Flag recurring complaints
complaints = analyzeFeedback(feedback);
if (complaints.contains("delivery delay")) {
    alertProductTeam();
}
41.10 Summary

Expert systems help optimize marketing strategies and customer engagement.

42.1 Load Forecasting

Predicts energy demand for grid management.

// Example: Forecast peak load for next day
peakLoad = forecastLoad("nextDay");
42.2 Energy Distribution

Optimizes energy flow in the grid.

// Example: Allocate energy to high-demand areas
allocateEnergy(demandAreas);
42.3 Fault Detection

Identifies faults in energy equipment.

// Example: Detect transformer failure signs
if (transformer.temperature > limit) {
    alertFault("transformer");
}
42.4 Renewable Energy Integration

Manages solar, wind, and other renewables.

// Example: Balance solar input with grid demand
balanceRenewable("solar");
42.5 Demand Response

Adjusts consumption based on supply.

// Example: Send incentives for off-peak usage
if (currentLoad > threshold) {
    sendIncentives("offPeak");
}
42.6 Energy Storage Management

Controls battery charge and discharge.

// Example: Charge batteries when supply high
if (supply > demand) {
    chargeBattery();
}
42.7 Emissions Monitoring

Tracks pollution levels from energy sources.

// Example: Alert if emissions exceed limits
if (emissions > maxAllowed) {
    triggerAlarm();
}
42.8 Cost Optimization

Minimizes energy costs.

// Example: Use cheaper energy sources during peak
switchEnergySource("cheapest");
42.9 User Consumption Analytics

Analyzes user energy consumption patterns.

// Example: Suggest energy-saving tips
if (userUsage > average) {
    suggestTips();
}
42.10 Summary

Expert systems optimize energy usage and integrate renewables.

43.1 Inventory Management

Monitors stock levels and sales rates.

// Example: Reorder product if stock low
if (product.stock < reorderLevel) {
    reorderProduct(product.id);
}
43.2 Pricing Strategy

Adjusts prices dynamically.

// Example: Increase price during high demand
if (demand > threshold) {
    increasePrice(product.id);
}
43.3 Customer Behavior Analysis

Studies buying patterns.

// Example: Recommend products based on purchase history
recommendProducts(customer.history);
43.4 Supply Chain Coordination

Coordinates suppliers and logistics.

// Example: Track deliveries and update stock
if (delivery.arrived) {
    updateInventory(delivery.products);
}
43.5 Fraud Prevention

Detects fraudulent transactions.

// Example: Flag suspicious returns
if (returns.frequency > limit) {
    flagFraud(customer.id);
}
43.6 Customer Support

Automates query handling.

// Example: Respond to product availability queries
if (query.type == "availability") {
    respond(product.stockStatus);
}
43.7 Marketing Campaigns

Targets customers with promotions.

// Example: Send promo to frequent buyers
if (customer.purchaseCount > 10) {
    sendPromo(customer.id);
}
43.8 Store Layout Optimization

Plans product placement for sales.

// Example: Place popular items near entrance
arrangeStoreLayout(popularItems);
43.9 Sales Forecasting

Predicts future sales.

// Example: Forecast monthly sales trends
forecast = salesForecast(monthlyData);
43.10 Summary

Expert systems improve retail efficiency and customer satisfaction.

44.1 Network Fault Diagnosis

Detects and diagnoses network issues.

// Example: Alert if link down
if (network.linkStatus == "down") {
    alertNetworkTeam();
}
44.2 Traffic Routing

Optimizes routing for data packets.

// Example: Choose least congested path
route = choosePath("leastCongestion");
44.3 Bandwidth Allocation

Distributes bandwidth efficiently.

// Example: Allocate more bandwidth during peak hours
if (time.isPeak()) {
    allocateBandwidth(highPriorityUsers);
}
44.4 Customer Service Automation

Automates support via chatbots.

// Example: Answer common billing queries
if (query.type == "billing") {
    respondBillingFAQs();
}
44.5 Fraud Detection

Identifies fraudulent calls or access.

// Example: Flag suspicious call patterns
if (call.pattern == "suspicious") {
    flagAccount();
}
44.6 Service Provisioning

Automates service activation and changes.

// Example: Activate new plan on request
if (request.type == "activate plan") {
    activatePlan(request.planId);
}
44.7 Billing Management

Calculates and issues bills.

// Example: Generate monthly invoice
generateInvoice(customer.id);
44.8 Performance Monitoring

Tracks network performance metrics.

// Example: Alert if latency exceeds limit
if (latency > threshold) {
    alertNetwork();
}
44.9 Regulatory Compliance

Ensures telecom operations meet regulations.

// Example: Audit call records
auditRecords();
44.10 Summary

Expert systems improve telecom reliability and customer experience.

45.1 Pollution Monitoring

Tracks pollution levels in air and water.

// Example: Alert if pollution exceeds safe levels
if (pollution.level > safeLimit) {
    alert("Pollution alert");
}
45.2 Waste Management

Optimizes waste collection and recycling.

// Example: Schedule pickup when bins full
if (bin.fillLevel > 90%) {
    schedulePickup(bin.id);
}
45.3 Resource Conservation

Recommends ways to save water and energy.

// Example: Suggest reduce water usage during drought
if (droughtCondition) {
    suggestAction("reduce water usage");
}
45.4 Environmental Impact Assessment

Evaluates effects of projects on environment.

// Example: Assess impact of new construction
impact = assessImpact(constructionProject);
45.5 Climate Modeling

Simulates climate change scenarios.

// Example: Model temperature rise over 50 years
model = simulateClimateChange(50);
45.6 Disaster Management

Predicts and manages natural disasters.

// Example: Alert for flood risk after heavy rain
if (rainfall > threshold) {
    alert("Flood risk");
}
45.7 Biodiversity Monitoring

Tracks species populations and habitats.

// Example: Report endangered species sightings
reportSighting(species);
45.8 Regulatory Compliance

Ensures environmental laws are followed.

// Example: Check factory emissions compliance
if (!factory.emissionsCompliant()) {
    issueFine(factory.id);
}
45.9 Public Awareness

Educates public on environmental issues.

// Example: Send tips for recycling
sendMessage(publicList, "Recycle tips");
45.10 Summary

Expert systems support sustainable environmental management.

46.1 Credit Scoring

Evaluates loan applicants based on credit history to determine risk.

// Example: Approve loan if credit score above threshold
if (applicant.creditScore >= 700) {
    approveLoan(applicant.id);
} else {
    rejectLoan(applicant.id);
}
46.2 Fraud Detection

Identifies unusual transactions that might indicate fraud.

// Example: Flag transaction if amount unusually high
if (transaction.amount > 10000 && !transaction.isVerified) {
    flagFraud(transaction.id);
}
46.3 Portfolio Management

Helps manage investment portfolios by balancing risk and returns.

// Example: Rebalance portfolio if risk exceeds limit
if (portfolio.risk > acceptableRisk) {
    rebalancePortfolio(portfolio.id);
}
46.4 Market Analysis

Analyzes market trends to guide investment decisions.

// Example: Suggest buy if stock trend is upward
if (stock.trend == "upward") {
    suggestBuy(stock.symbol);
}
46.5 Loan Approval Automation

Automates decision-making for loan approvals based on rules.

// Example: Approve loan if income sufficient and no defaults
if (applicant.income >= requiredIncome && !applicant.hasDefaults) {
    approveLoan(applicant.id);
}
46.6 Risk Assessment

Assesses financial risks for investments or loans.

// Example: Calculate risk score based on multiple factors
riskScore = calculateRisk(applicant.financialData);
if (riskScore < threshold) {
    approveLoan(applicant.id);
}
46.7 Tax Compliance

Ensures all transactions and reports meet tax regulations.

// Example: Verify tax report completeness
if (taxReport.isComplete()) {
    submitReport();
} else {
    requestMoreInfo();
}
46.8 Budget Planning

Helps individuals or companies plan budgets effectively.

// Example: Alert if expenses exceed budget
if (expenses > budget) {
    alertUser("Budget exceeded");
}
46.9 Loan Repayment Monitoring

Tracks repayments and sends reminders for overdue payments.

// Example: Send reminder if payment overdue
if (payment.dueDate < today && !payment.isPaid) {
    sendReminder(applicant.id);
}
46.10 Summary

Expert systems in finance improve decision-making, reduce fraud, and enhance compliance.

47.1 Diagnosis Support

Assists doctors in diagnosing diseases by analyzing symptoms.

// Example: Suggest diagnosis if symptoms match disease profile
if (patient.symptoms.includes("fever") && patient.symptoms.includes("cough")) {
    suggestDiagnosis("flu");
}
47.2 Treatment Recommendations

Recommends treatments based on diagnosis and patient history.

// Example: Recommend medication based on diagnosis
if (diagnosis == "flu") {
    recommendTreatment("antiviral drugs");
}
47.3 Patient Monitoring

Tracks vital signs and alerts for abnormalities.

// Example: Alert if heart rate too high
if (patient.heartRate > 100) {
    alertMedicalStaff(patient.id);
}
47.4 Drug Interaction Checking

Checks for harmful interactions between prescribed drugs.

// Example: Warn if two drugs have negative interaction
if (drugA.interactsWith(drugB)) {
    alertDoctor();
}
47.5 Medical Imaging Analysis

Assists in interpreting X-rays, MRIs, and other images.

// Example: Detect abnormality in X-ray image
if (imageAnalysis.detects("tumor")) {
    flagForReview();
}
47.6 Appointment Scheduling

Optimizes scheduling to reduce patient wait times.

// Example: Schedule appointment when doctor is free
if (doctor.isAvailable(timeSlot)) {
    bookAppointment(patient.id, timeSlot);
}
47.7 Billing and Insurance Processing

Automates billing and claims processing.

// Example: Generate invoice after treatment
generateInvoice(patient.id);
47.8 Health Record Management

Maintains and secures patient medical records.

// Example: Update patient record with new test results
updateRecord(patient.id, testResults);
47.9 Preventive Care Recommendations

Suggests screenings or lifestyle changes to prevent disease.

// Example: Recommend flu shot before winter
if (season == "fall") {
    recommend("flu vaccination");
}
47.10 Summary

Expert systems improve patient care, diagnosis, and healthcare efficiency.

48.1 Production Line Control

Monitors and adjusts production lines for efficiency.

// Example: Pause line if defect rate too high
if (defectRate > 5%) {
    pauseProductionLine();
}
48.2 Equipment Maintenance

Schedules preventive maintenance to reduce downtime.

// Example: Schedule maintenance after 1000 hours of use
if (equipment.hoursUsed >= 1000) {
    scheduleMaintenance(equipment.id);
}
48.3 Quality Assurance

Checks product quality against standards.

// Example: Reject batch if quality below threshold
if (batch.qualityScore < 90) {
    rejectBatch(batch.id);
}
48.4 Inventory Control

Manages raw materials and finished goods stock.

// Example: Reorder raw materials if below minimum
if (rawMaterial.stock < minimumStock) {
    placeOrder(rawMaterial.id);
}
48.5 Process Optimization

Analyzes production processes to improve efficiency.

// Example: Adjust process parameters to reduce waste
adjustParameters({temperature: optimalTemp, speed: optimalSpeed});
48.6 Worker Safety Monitoring

Detects unsafe conditions and alerts workers.

// Example: Alert if toxic gas detected
if (gasSensor.level > safeLimit) {
    alertWorkers();
}
48.7 Energy Consumption Management

Monitors and reduces energy usage.

// Example: Turn off machines during breaks
if (breakTime) {
    shutdownMachines();
}
48.8 Production Scheduling

Plans production to meet demand efficiently.

// Example: Schedule jobs based on priority
scheduleJobs(jobs, priorityCriteria);
48.9 Waste Reduction

Identifies and minimizes material waste.

// Example: Reduce scrap by adjusting cutting patterns
adjustCuttingPatterns();
48.10 Summary

Expert systems optimize manufacturing processes and improve safety.

49.1 Automated Response

Uses chatbots to answer common customer questions automatically.

// Example: Respond with FAQ answer
if (query.type == "FAQ") {
    respondWithFAQ(query);
}
49.2 Complaint Handling

Prioritizes and routes customer complaints for faster resolution.

// Example: Route urgent complaints to senior staff
if (complaint.priority == "high") {
    routeToStaff("senior");
}
49.3 Feedback Analysis

Analyzes customer feedback to identify improvement areas.

// Example: Flag recurring complaint topics
topics = analyzeFeedback(feedback);
if (topics.contains("delivery delay")) {
    alertManagement();
}
49.4 Service Personalization

Customizes responses based on customer profile and history.

// Example: Greet returning customer by name
if (customer.isReturning) {
    greetCustomer(customer.name);
}
49.5 Issue Prediction

Predicts potential customer issues to proactively address them.

// Example: Notify customer of possible service outage
if (system.status == "unstable") {
    notifyCustomers("Possible outage");
}
49.6 Knowledge Base Management

Keeps FAQs and help articles up to date.

// Example: Update knowledge base with new solutions
updateKnowledgeBase(newSolutions);
49.7 Escalation Management

Automatically escalates unresolved issues.

// Example: Escalate if issue unresolved after 24 hours
if (issue.unresolvedDuration > 24) {
    escalateIssue(issue.id);
}
49.8 Customer Satisfaction Monitoring

Monitors satisfaction scores and triggers actions if low.

// Example: Send survey if satisfaction below threshold
if (survey.score < 3) {
    sendFollowUpSurvey(customer.id);
}
49.9 Training and Support

Provides training material to customer service agents.

// Example: Recommend training for agents on new product
if (product.updated) {
    assignTraining("new product");
}
49.10 Summary

Expert systems enhance customer service efficiency and satisfaction.

50.1 Route Optimization

Calculates the best routes to reduce travel time and cost.

// Example: Choose shortest path avoiding traffic
route = findOptimalRoute(start, destination, trafficData);
50.2 Fleet Management

Tracks vehicles and schedules maintenance.

// Example: Alert for vehicle maintenance due
if (vehicle.mileage > maintenanceThreshold) {
    scheduleMaintenance(vehicle.id);
}
50.3 Traffic Management

Monitors traffic flow and adjusts signals accordingly.

// Example: Change signal timing based on congestion
if (trafficDensity > threshold) {
    adjustSignalTiming();
}
50.4 Driver Assistance

Provides real-time alerts and recommendations to drivers.

// Example: Warn driver about sharp turn ahead
if (upcomingTurn.sharpness > limit) {
    alertDriver("Sharp turn ahead");
}
50.5 Accident Detection

Detects accidents and alerts emergency services.

// Example: Send alert if sudden stop detected
if (vehicle.acceleration < suddenStopThreshold) {
    notifyEmergencyServices(vehicle.location);
}
50.6 Public Transport Scheduling

Optimizes bus and train schedules based on demand.

// Example: Add extra bus during peak hours
if (passengerCount > peakThreshold) {
    deployAdditionalBus(route.id);
}
50.7 Cargo Tracking

Monitors shipment status and location.

// Example: Update cargo status in real-time
updateCargoStatus(cargo.id, currentLocation);
50.8 Emission Control

Monitors vehicle emissions and suggests actions.

// Example: Alert driver to reduce idling
if (engine.idleTime > limit) {
    alertDriver("Reduce engine idling");
}
50.9 Safety Compliance

Ensures vehicles and drivers meet safety regulations.

// Example: Verify driver license validity
if (!driver.license.isValid()) {
    restrictVehicleAccess(driver.id);
}
50.10 Summary

Expert systems in transportation improve safety, efficiency, and environmental impact.

51.1 What is Django REST Framework (DRF)?

DRF is a powerful toolkit to build Web APIs easily with Django, supporting serialization, authentication, and more.

51.2 Installing DRF
pip install djangorestframework
51.3 Adding DRF to Installed Apps
# settings.py
INSTALLED_APPS = [
    # other apps
    'rest_framework',
]
51.4 Creating a Simple Serializer
from rest_framework import serializers
from myapp.models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'
51.5 Writing a Basic API View
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import Item
from .serializers import ItemSerializer

class ItemList(APIView):
    def get(self, request):
        items = Item.objects.all()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)
51.6 URL Routing for API
# urls.py
from django.urls import path
from .views import ItemList

urlpatterns = [
    path('api/items/', ItemList.as_view(), name='item-list'),
]

52.1 Serializer vs ModelSerializer

Serializer defines fields manually; ModelSerializer auto-generates fields from model.

52.2 Defining a Custom Serializer
from rest_framework import serializers

class CustomSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    age = serializers.IntegerField()
52.3 Validation in Serializers
class UserSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def validate_email(self, value):
        if "example.com" not in value:
            raise serializers.ValidationError("Must be an example.com email")
        return value
52.4 Serializer Relationships
class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer(read_only=True)
    
    class Meta:
        model = Book
        fields = ['title', 'author']
52.5 Nested Serializers

Support complex data by nesting serializers.

52.6 Serializer Methods
class ItemSerializer(serializers.ModelSerializer):
    is_expensive = serializers.SerializerMethodField()

    def get_is_expensive(self, obj):
        return obj.price > 100

53.1 What are Viewsets?

Viewsets combine logic for multiple views into one class, reducing code duplication.

53.2 Simple ModelViewSet
from rest_framework import viewsets
from myapp.models import Item
from .serializers import ItemSerializer

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
53.3 Using Routers
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from .views import ItemViewSet

router = DefaultRouter()
router.register(r'items', ItemViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
]
53.4 Benefits of Viewsets and Routers

Automatically provide CRUD endpoints with less code.

53.5 Customizing Actions
from rest_framework.decorators import action
from rest_framework.response import Response

class ItemViewSet(viewsets.ModelViewSet):
    # ...

    @action(detail=True, methods=['post'])
    def set_price(self, request, pk=None):
        item = self.get_object()
        item.price = request.data.get('price')
        item.save()
        return Response({'status': 'price set'})

54.1 Built-in Authentication Classes

DRF provides TokenAuthentication, SessionAuthentication, BasicAuthentication.

54.2 Setting Authentication Classes
# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}
54.3 Permissions Classes

Control who can access APIs, e.g. IsAuthenticated, AllowAny, IsAdminUser.

54.4 Using Permissions
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class SecureView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'message': 'Hello, authenticated user!'})
54.5 Creating Custom Permissions
from rest_framework.permissions import BasePermission

class IsOwner(BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user
54.6 Token Authentication Example
# Install
pip install djangorestframework-simplejwt

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

55.1 Pagination Overview

Break large result sets into pages to improve performance and UX.

55.2 Built-in Pagination Classes

PageNumberPagination, LimitOffsetPagination, CursorPagination.

55.3 Using Pagination in Settings
# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
}
55.4 Filtering with django-filter

Install django-filter to add filtering capabilities.

pip install django-filter
55.5 Enabling Filtering in DRF
# settings.py
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
}
55.6 Example FilterSet
import django_filters
from myapp.models import Item

class ItemFilter(django_filters.FilterSet):
    price_min = django_filters.NumberFilter(field_name="price", lookup_expr='gte')
    price_max = django_filters.NumberFilter(field_name="price", lookup_expr='lte')

    class Meta:
        model = Item
        fields = ['price_min', 'price_max']
55.7 Using FilterSet in ViewSet
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend
from myapp.models import Item
from .serializers import ItemSerializer
from .filters import ItemFilter

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = ItemFilter

56.1 What is Throttling?

Throttling limits the rate of requests to prevent abuse and ensure fair resource usage.

56.2 Built-in Throttling Classes

Includes AnonRateThrottle, UserRateThrottle, ScopedRateThrottle.

56.3 Enabling Throttling in Settings
# settings.py
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day',
    }
}
56.4 Custom Throttle Class Example
from rest_framework.throttling import SimpleRateThrottle

class CustomIPThrottle(SimpleRateThrottle):
    scope = 'custom'

    def get_cache_key(self, request, view):
        return self.get_ident(request)
56.5 Applying Custom Throttle to a View
from rest_framework.views import APIView
from rest_framework.response import Response

class MyView(APIView):
    throttle_classes = [CustomIPThrottle]

    def get(self, request):
        return Response({'message': 'Throttled API'})
56.6 Monitoring Throttling

Django REST Framework returns HTTP 429 when throttled.

57.1 Importance of Testing APIs

Ensures reliability, correctness, and regression prevention for your API endpoints.

57.2 Using APIClient
from rest_framework.test import APIClient
client = APIClient()

response = client.get('/api/items/')
print(response.status_code)
print(response.data)
57.3 Writing a Test Case
from rest_framework.test import APITestCase
from django.urls import reverse

class ItemTests(APITestCase):
    def test_get_items(self):
        url = reverse('item-list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
57.4 Testing POST Requests
def test_create_item(self):
    url = reverse('item-list')
    data = {'name': 'New Item', 'price': 50}
    response = self.client.post(url, data, format='json')
    self.assertEqual(response.status_code, 201)
57.5 Authentication in Tests
self.client.force_authenticate(user=self.user)
response = self.client.get(url)

58.1 Why Customize Pagination?

To tailor API responses to your clients’ needs with custom page sizes, formats, or metadata.

58.2 Custom PageNumberPagination
from rest_framework.pagination import PageNumberPagination

class CustomPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'
    max_page_size = 20
58.3 Applying Custom Pagination
from rest_framework import viewsets
from myapp.models import Item
from .serializers import ItemSerializer

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    pagination_class = CustomPagination
58.4 Response Structure

Paginated responses include keys like count, next, previous, and results.

58.5 LimitOffsetPagination Example
from rest_framework.pagination import LimitOffsetPagination

class LimitOffsetPaginationCustom(LimitOffsetPagination):
    default_limit = 10
    max_limit = 50

59.1 Scoped Throttling

Use different throttling rates per view using scopes.

59.2 Defining Scopes in Settings
# settings.py
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.ScopedRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'user': '1000/day',
        'anon': '100/day',
        'custom_scope': '10/minute',
    }
}
59.3 Applying Scope in View
from rest_framework.views import APIView

class CustomThrottleView(APIView):
    throttle_scope = 'custom_scope'

    def get(self, request):
        return Response({'message': 'Scoped throttle applied'})
59.4 Combining Multiple Throttles

DRF checks all throttles; if any fails, request is blocked.

59.5 Monitoring and Logging Throttle Hits

Implement logging in custom throttle classes for audit.

60.1 Why Version Your API?

Maintain backward compatibility while evolving APIs.

60.2 Versioning Schemes

URL path versioning, query parameter versioning, header versioning.

60.3 Enabling Versioning in Settings
# settings.py
REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
}
60.4 URLPathVersioning Example
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView

class MyView(APIView):
    versioning_class = URLPathVersioning

    def get(self, request):
        version = request.version
        return Response({'version': version})
60.5 Using Version in URLs
from django.urls import path

urlpatterns = [
    path('api/v1/items/', MyView.as_view(), name='item-list-v1'),
    path('api/v2/items/', MyView.as_view(), name='item-list-v2'),
]
60.6 Handling Multiple Versions

Route requests to different serializers or logic based on version.