Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
# Django is installed via pip:
pip install django
Install Django using pip to start building web applications.
# Open terminal and run:
pip install django
# Verify installation
django-admin --version
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
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
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
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!')
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
]
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!'
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>
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
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()
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
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)
To access admin, create a superuser account.
# Create superuser
python manage.py createsuperuser
# Follow prompts for username, email, password
Access admin panel to add, edit, delete posts.
# Run server
python manage.py runserver
# Visit http://127.0.0.1:8000/admin/ and login
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()
Create new records via code.
>> post = Post(title='First Post', content='Hello world!')
>> post.save()
Modify existing database entries.
>> post = Post.objects.get(id=1)
>> post.title = 'Updated Title'
>> post.save()
Remove records from the database.
>> post = Post.objects.get(id=1)
>> post.delete()
Models connect your app to the database. Next, learn about views and templates to display this data.
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})
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>
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'),
]
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')),
]
Django templates use tags to add logic and output.
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
{% endfor %}
Views send data to templates via context dictionaries.
return render(request, 'template.html', {'key': value})
Serve CSS, JavaScript, and images using static files.
# settings.py
STATIC_URL = '/static/'
# In template:
<link rel=\"stylesheet\" href=\"{% static 'css/style.css' %}\">
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 %}
Use Django debug mode and error messages to fix issues.
# settings.py
DEBUG = True
# Check console errors and template syntax
Views and templates handle displaying dynamic content. Next, learn forms to interact with users.
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)
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})
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>
Django automatically validates form data.
# form.is_valid() checks required fields and types
# Errors accessible in template as {{ form.errors }}
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']
Save form data directly to the database.
# views.py
if request.method == 'POST':
form = PostModelForm(request.POST)
if form.is_valid():
form.save()
Show validation errors to users.
# In template
{{ form.non_field_errors }}
{{ form.field_name.errors }}
Redirect to another page after successful form submission.
from django.shortcuts import redirect
return redirect('post_list')
Handle file uploads with forms.
# forms.py
file = forms.FileField()
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
Forms allow user input handling. Next, learn user authentication and permissions.
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 %}
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 %}
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 %}
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 %}
Load static files in templates.
{% raw %}{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">{% endraw %}
Place static files in app-level or project-level static directories.
Use collectstatic
to gather all static files in one place for deployment.
python manage.py collectstatic
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, '')
Pass variables from views to templates.
def post_list(request):
posts = Post.objects.all()
return render(request, 'post_list.html', {'posts': posts})
Django templates separate logic and presentation, making your code cleaner and easier to maintain.
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)
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]
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
Filter data with methods like filter(), exclude(), and get().
posts = Post.objects.filter(title__icontains='django')
Perform calculations on data like count, average, max, and min.
from django.db.models import Count
post_count = Post.objects.aggregate(Count('id'))
Access related models via Django ORM.
author = Author.objects.get(id=1)
books = author.book_set.all()
Create custom QuerySets for reusable queries.
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
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)
Create your own model field types.
from django.db import models
class PhoneNumberField(models.CharField):
pass # Custom validation can be added here
Advanced model concepts allow powerful data handling. Next, learn Django REST Framework for APIs.
A toolkit to build Web APIs easily with Django.
# Install DRF
pip install djangorestframework
Add 'rest_framework' to settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
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__'
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)
Simplify routing with ViewSets and Routers.
from rest_framework import viewsets
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
Wire your API routes.
from rest_framework.routers import DefaultRouter
from .views import PostViewSet
router = DefaultRouter()
router.register(r'posts', PostViewSet)
Secure your APIs with token or session auth.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
}
Use tools like Postman or curl to test API endpoints.
curl http://127.0.0.1:8000/posts/
Handle large result sets by paginating API responses.
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
DRF enables API building. Next, learn testing and deployment.
Testing ensures your app works as expected and prevents bugs.
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')
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)
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']
Test multiple components together.
Automate browser testing for UI interactions.
# Install selenium
pip install selenium
Automate tests with CI tools like GitHub Actions.
Use mocking to isolate tests from third-party APIs.
Measure how much of your code is tested.
pip install coverage
coverage run manage.py test
coverage report
Testing improves code quality and reliability.
Collect static files and configure settings for production.
python manage.py collectstatic
Turn off debug mode in production for security.
# settings.py
DEBUG = False
Use WSGI servers like Gunicorn or uWSGI.
pip install gunicorn
gunicorn myproject.wsgi
Use production-grade databases like PostgreSQL.
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '',
}
}
Set the domains your app can serve.
# settings.py
ALLOWED_HOSTS = ['yourdomain.com']
Use SSL certificates to secure traffic.
Keep secrets out of source code with env vars.
Track errors and performance using tools like Sentry.
Use load balancers and caching for performance.
Deployment requires careful configuration for security and performance.
Middleware processes requests/responses globally.
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
...
]
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
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)
Improve performance with caching.
# settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
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}!'
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'})
Manage file uploads and serve files.
# models.py
file = models.FileField(upload_to='uploads/')
Create a custom user model for flexibility.
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
Use signals for decoupled app interactions.
Advanced features let you customize Django to your needs.
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()
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']
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
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})
Show form validation errors in templates.
{% raw %}{{ form.non_field_errors }}
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}{% endraw %}
Customize input elements for better UI.
class PostForm(ModelForm):
class Meta:
model = Post
widgets = {
'content': forms.Textarea(attrs={'rows':4, 'cols':15}),
}
Manage multiple forms on a single page.
from django.forms import formset_factory
ContactFormSet = formset_factory(ContactForm, extra=3)
Use CSRF tokens to protect against attacks.
{% raw %}<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>{% endraw %}
Handle file uploads with forms and models.
file = forms.FileField()
# In view handle request.FILES
form = UploadForm(request.POST, request.FILES)
Forms handle user input and validation with ease.
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')
Create views and forms to register users.
from django.contrib.auth.forms import UserCreationForm
form = UserCreationForm()
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)
Reset and change passwords securely.
from django.contrib.auth.forms import PasswordChangeForm
form = PasswordChangeForm(user=request.user)
Assign permissions and groups for access control.
from django.contrib.auth.models import Group, Permission
group = Group.objects.create(name='Editors')
Customize User model for extra fields.
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
phone = models.CharField(max_length=15, blank=True)
Customize how users are authenticated.
Extend user info with a profile model.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank=True)
Django middleware handles sessions and user authentication automatically.
Django’s authentication framework is robust and extensible.
Middleware processes requests and responses globally in Django.
Django provides security, session, authentication, and other 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
Order in settings.py matters, middleware runs top-down on request and bottom-up on response.
def __call__(self, request):
response = self.get_response(request)
response['X-Custom-Header'] = 'Value'
return response
Catch exceptions and provide custom error pages.
Authentication middleware attaches the user to request objects.
Keep middleware efficient to avoid slowing down requests.
Use middleware from libraries for features like CORS, compression.
Middleware is powerful for global request/response processing.
Signals allow decoupled apps to get notified about events.
Common signals include pre_save, post_save, pre_delete, post_delete.
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}')
Connect signals using decorators or connect() method.
Automatically update or create related objects.
Avoid heavy processing in signal handlers to keep app responsive.
Test signal functionality with unit tests.
Remove signal handlers if needed to avoid side effects.
Define your own signals for custom app logic.
Signals help keep apps modular and decoupled.
Speed up your site by caching expensive computations and queries.
# settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
from django.core.cache import cache
cache.set('my_key', 'hello', 30) # cache for 30 seconds
value = cache.get('my_key')
Cache parts of templates.
{% raw %}{% load cache %}
{% cache 600 sidebar %}
...sidebar content...
{% endcache %}{% endraw %}
Cache entire views for performance.
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def my_view(request):
...
Cache anything with custom keys.
Plan when to clear or update cache entries.
Use external cache backends for production.
Cache session data for faster access.
Caching is vital for scaling Django apps.
Review how signals help with decoupled communication.
Examples: sending notifications, updating caches, logging.
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_delete, sender=Post)
def log_deletion(sender, instance, **kwargs):
print(f"Post deleted: {instance.title}")
Clear or refresh cache when data changes.
Keep handlers fast and non-blocking.
Write tests that ensure signals fire correctly.
Use logging or breakpoints to debug signal handlers.
Consider explicit calls or messaging queues for complex workflows.
Signals are useful but require care for maintainability.
Secure your APIs with authentication mechanisms.
Uses Django’s session framework.
Simple token-based authentication.
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=user)
Use JSON Web Tokens for stateless auth.
Third-party OAuth2 providers integration.
Implement your own authentication class.
Define who can access what in your API.
Limit request rates to prevent abuse.
Write tests to verify auth functionality.
Proper authentication is critical for API security.
Convert complex data types to JSON and back.
from rest_framework import serializers
class PostSerializer(serializers.Serializer):
title = serializers.CharField(max_length=100)
content = serializers.CharField()
Serializer tied directly to models.
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'content']
Use validate_fieldname or validate() methods.
Serialize related objects inside main serializers.
Add custom read-only fields with get_
Use PrimaryKeyRelatedField or StringRelatedField.
Optimize serialization for large datasets.
Write tests to validate serializer behavior.
Serializers are essential for API data exchange.
Viewsets combine logic for multiple views in a single class.
Automatically generate URL conf for viewsets.
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'posts', PostViewSet)
CRUD operations in one class.
Add extra actions using @action decorator.
Handle nested resource routing.
Paginate large querysets in APIs.
Allow filtering and searching on endpoints.
Limit API request rates per user.
Secure your API endpoints.
Viewsets and routers simplify API design.
QuerySets represent collections of objects from the database.
Post.objects.all()
Post.objects.filter(author='john')
Post.objects.filter(published=True).exclude(title__icontains='draft')
Calculate sums, averages, counts.
from django.db.models import Count
Post.objects.aggregate(total=Count('id'))
Add calculated fields to QuerySets.
from django.db.models import Count
Post.objects.annotate(comment_count=Count('comments'))
Optimize queries by joining related tables.
Post.objects.select_related('author')
Fetch many-to-many and reverse foreign keys efficiently.
Post.objects.prefetch_related('tags')
Execute raw SQL when needed.
Post.objects.raw('SELECT * FROM blog_post WHERE published = %s', [True])
Extend QuerySets with custom methods.
class PostManager(models.Manager):
def published(self):
return self.filter(published=True)
Mastering QuerySets improves app performance and flexibility.
Signals allow decoupled apps to react to certain actions in Django.
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!')
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()
Multiple signals can be triggered for one event.
Temporarily disconnect signals to avoid side effects during tests.
post_save.disconnect(receiver=profile_updated, sender=Profile)
Create your own signal for app-specific events.
from django.dispatch import Signal
order_completed = Signal(providing_args=["order_id"])
order_completed.send(sender=self.__class__, order_id=order.id)
Logging, notifications, cache updates, etc.
Avoid heavy processing and circular signals.
Signals help keep code modular but require careful use.
Ensure code correctness and prevent regressions.
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')
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')
def test_form_valid(self):
data = {'name': 'John', 'email': 'john@example.com'}
form = ContactForm(data=data)
self.assertTrue(form.is_valid())
Preload test data using fixtures or setUp methods.
Prepare and clean up test environment.
def setUp(self):
self.user = User.objects.create_user('testuser')
Use Django's test database for isolated tests.
python manage.py test
Integrate tests into your CI pipeline for automation.
Testing improves reliability and maintainability.
from django.db.models import Q
Post.objects.filter(Q(title__icontains='django') | Q(content__icontains='framework'))
Perform database operations without fetching objects.
from django.db.models import F
Post.objects.update(views=F('views') + 1)
Use subqueries to filter or annotate.
from django.db.models import Exists, OuterRef
comments = Comment.objects.filter(post=OuterRef('pk'))
Post.objects.annotate(has_comments=Exists(comments))
Count, Sum, Avg, Max, Min.
Advanced SQL window functions for ranking, running totals.
Use raw() for complex queries not supported by ORM.
Use select_related, prefetch_related to reduce DB hits.
Add reusable filters or methods.
Master advanced querying for efficient apps.
Break large querysets into manageable pages.
Basic page number based pagination.
from rest_framework.pagination import PageNumberPagination
class MyPagination(PageNumberPagination):
page_size = 10
Supports limit and offset parameters.
Use cursor-based pagination for large datasets.
from rest_framework import viewsets
class PostViewSet(viewsets.ModelViewSet):
pagination_class = MyPagination
queryset = Post.objects.all()
serializer_class = PostSerializer
Customize the pagination response format.
Combine pagination with filters and searches.
Pagination improves response time and reduces memory.
Write tests to verify page sizes and content.
Pagination is essential for scalable APIs.
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 %}
Use built-in and custom tags.
Modify variables with filters.
{% raw %}{{ name|lower }}{% endraw %}
Create reusable logic in templates.
Render a sub-template with its own context.
{% raw %}{% with total=business.employees.count %}Total Employees: {{ total }}{% endwith %}{% endraw %}
{% raw %}{% if user.is_authenticated %}Welcome!{% else %}Please login.{% endif %}{% endraw %}
{% raw %}{% for item in list %}{{ item }}{% endfor %}{% endraw %}
Use Django debug toolbar or logging.
Master templates to build dynamic pages.
Adds WebSocket and asynchronous support to Django.
pip install channels
Set ASGI application in settings.py.
ASGI_APPLICATION = 'myproject.asgi.application'
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}))
from django.urls import re_path
from .consumers import ChatConsumer
websocket_urlpatterns = [
re_path(r'ws/chat/$', ChatConsumer.as_asgi()),
]
daphne myproject.asgi:application
Send messages to groups of connections.
Access database asynchronously in consumers.
Chat apps, live notifications, real-time dashboards.
Django Channels extends Django with async and real-time capabilities.
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
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/;
}
}
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.
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)
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',
},
}
}
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;
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,
},
},
}
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
...
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
Following deployment best practices ensures your Django app runs securely, reliably, and efficiently in production.
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 }}
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 %}
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)
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'
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')
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
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
]
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)
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
Implementing these security best practices helps protect your Django app from common web vulnerabilities.
Caching reduces database queries and speeds up page load by storing results temporarily.
Django supports multiple cache backends: in-memory, file-based, Memcached, Redis.
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
...
Cache only parts of a template (fragments) to optimize performance.
{% raw %}
{% cache 600 sidebar %}
{% endcache %}
{% endraw %}
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')
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')
Use descriptive and unique keys to avoid collisions in shared caches.
Use Redis or Memcached to share cache between multiple servers in a scalable setup.
Track cache hit/miss ratios and optimize accordingly.
Caching is essential to improve Django app performance and scalability.
Internationalization (i18n) is preparing your app to support multiple languages and regional settings.
Set USE_I18N = True
and configure available languages.
# settings.py
USE_I18N = True
LANGUAGES = [
('en', 'English'),
('fr', 'French'),
('es', 'Spanish'),
]
Use Django's gettext
function to mark strings for translation.
from django.utils.translation import gettext as _
message = _("Welcome to my site")
Generate message files for a language (e.g., French) with:
django-admin makemessages -l fr
Translate the generated .po
files, then compile with:
django-admin compilemessages
Translate strings in templates using the {% trans %}
tag.
{% raw %}
{% trans "Hello World" %}
{% endraw %}
Add LocaleMiddleware to detect user's language preference automatically.
# settings.py
MIDDLEWARE = [
'django.middleware.locale.LocaleMiddleware',
# other middleware
]
Use Django's localization filters in templates:
{% raw %}
{{ value|localize }}
{{ date_value|date:"SHORT_DATE_FORMAT" }}
{% endraw %}
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()
Internationalization allows your Django app to reach a global audience by supporting multiple languages and locales.
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);
}
Inspects products for defects and suggests corrections.
// Example: If defect detected in batch, notify technician
if (batch.hasDefect()) {
notifyTechnician(batch.id);
}
Forecasts equipment failures before they occur.
// Example: If vibration exceeds threshold, predict fault
if (machine.vibration > threshold) {
alert("Possible machine fault");
}
Keeps track of raw material usage.
// Example: Reorder if steel stock less than 10 tons
if (inventory.steel < 10) {
reorder("steel");
}
Improves efficiency by analyzing process steps.
// Example: Remove redundant process step C
if (process.hasRedundantStep("C")) {
process.removeStep("C");
}
Minimizes energy consumption across machines.
// Example: Schedule heater to run at off-peak hours
if (currentTime.isOffPeak()) {
heater.run();
}
Assigns workers and tools efficiently.
// Example: Assign worker A to station 3
assignWorker("WorkerA", "Station3");
Detects and reduces material waste in production.
// Example: Suggest trimming 2cm less to save material
if (wasteRate > acceptableLevel) {
suggestTrimAdjustment(-2);
}
Flags unsafe conditions or processes.
// Example: Trigger alert if heat exceeds safe threshold
if (temperature > safeThreshold) {
triggerAlert("Overheat detected");
}
Analyzes process flow for delays or bottlenecks.
// Example: If step D delayed, increase staffing
if (stepD.delay > maxDelay) {
increaseStaff("StepD");
}
Evaluates student performance and recommends improvements.
// Example: Suggest practice if score below 60%
if (student.score < 60) {
recommend("practice set");
}
Adapts lessons based on student learning pace.
// Example: Skip review for fast learners
if (student.learningSpeed == "fast") {
skipLesson("review");
}
Recommends careers based on interests and performance.
// Example: Suggest engineering for good math skills
if (student.skills.math > threshold) {
recommendCareer("Engineering");
}
Suggests relevant materials and resources.
// Example: Recommend loop tutorials if learning Python
if (student.learningTopic == "Python") {
recommendMaterial("loops tutorial");
}
Scans for copied content in assignments.
// Example: Flag assignment if similarity over 85%
if (assignment.similarityScore > 85) {
flagAssignment(assignment.id);
}
Helps educators with lesson planning and assessments.
// Example: Provide exercises on Algebra topic
if (lesson.topic == "Algebra") {
provideExercises("Algebra");
}
Processes student feedback to improve courses.
// Example: Suggest more interactive sessions if feedback low
if (feedback.interactivityScore < threshold) {
suggestChange("more interactive sessions");
}
Tracks and analyzes student attendance patterns.
// Example: Send notification after 3 absences
if (student.absences >= 3) {
sendNotification(student.id, "Attendance warning");
}
Recommends curriculum changes based on trends.
// Example: Add AI module to Computer Science course
if (industryTrend == "AI") {
addCurriculumModule("CS", "AI");
}
Adapts content for students with disabilities.
// Example: Use audio resources for dyslexic students
if (student.hasDisability("dyslexia")) {
useResource("audio");
}
Assists doctors by suggesting possible diagnoses.
// Example: Suggest diagnosis if symptoms match
if (patient.symptoms.containsAll(["fever","cough"])) {
suggestDiagnosis("flu");
}
Recommends treatments based on diagnosis.
// Example: Recommend antibiotics for bacterial infection
if (diagnosis == "bacterial infection") {
recommendTreatment("antibiotics");
}
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");
}
Tracks vital signs and alerts on abnormalities.
// Example: Alert if heart rate too high
if (patient.heartRate > 120) {
sendAlert("High heart rate");
}
Analyzes images for abnormalities.
// Example: Flag tumor detected in X-ray image
if (imageAnalysis.detect("tumor")) {
flagImage(patient.id, "tumor");
}
Optimizes doctor appointment times.
// Example: Schedule follow-up 2 weeks after treatment
scheduleAppointment(patient.id, treatmentDate.addWeeks(2));
Keeps and updates patient history.
// Example: Add new diagnosis to patient record
patient.record.addDiagnosis(diagnosis);
Assesses risk factors for diseases.
// Example: High risk if family history of diabetes
if (patient.familyHistory.contains("diabetes")) {
markRisk(patient.id, "high");
}
Guides doctors through treatment protocols.
// Example: Follow protocol if patient has condition X
if (patient.condition == "X") {
followProtocol("ProtocolX");
}
Expert systems improve healthcare decision-making.
Evaluates creditworthiness of applicants.
// Example: Approve loan if credit score above threshold
if (applicant.creditScore > 700) {
approveLoan(applicant.id);
}
Detects suspicious transaction patterns.
// Example: Flag transaction if amount unusually high
if (transaction.amount > 10000) {
flagTransaction(transaction.id);
}
Suggests investment options based on risk profile.
// Example: Recommend bonds for low-risk investors
if (investor.riskProfile == "low") {
recommendInvestment("bonds");
}
Automates loan processing decisions.
// Example: Auto-approve if income and credit good
if (applicant.income > 50000 && applicant.creditScore > 700) {
autoApproveLoan(applicant.id);
}
Optimizes asset allocation for investors.
// Example: Rebalance portfolio monthly
if (today == portfolio.rebalanceDate) {
rebalancePortfolio(investor.id);
}
Analyzes financial risks.
// Example: Flag high exposure to volatile stocks
if (portfolio.volatility > threshold) {
alert("High risk exposure");
}
Ensures regulatory compliance.
// Example: Check transactions against compliance rules
if (!transaction.compliesWithRules()) {
blockTransaction(transaction.id);
}
Calculates taxes automatically.
// Example: Calculate tax for given income
tax = calculateTax(income);
Automates responses to common queries.
// Example: Auto-reply to FAQs
if (customer.query in faqList) {
sendAutoReply(customer.id, faqList[query]);
}
Expert systems streamline financial operations and decision-making.
Answers common questions automatically.
// Example: Return canned answer for known question
if (customer.question in faq) {
answer = faq[customer.question];
}
Assigns priority to support tickets.
// Example: Mark ticket urgent if customer is VIP
if (ticket.customerStatus == "VIP") {
ticket.priority = "High";
}
Interacts with customers using AI chatbots.
// Example: Respond to greeting message
if (message == "hello") {
respond("Hello! How can I help you?");
}
Analyzes customer sentiment to route requests.
// Example: Route angry messages to senior staff
if (sentiment == "angry") {
routeTo("Senior Support");
}
Maintains and updates support articles.
// Example: Add new article when product updated
if (product.updated) {
addKnowledgeBaseArticle("New features");
}
Automates escalation processes.
// Example: Escalate ticket after 48 hours unresolved
if (ticket.age > 48 hours && !ticket.resolved) {
escalate(ticket.id);
}
Collects customer feedback post-resolution.
// Example: Send survey after ticket closed
if (ticket.status == "Closed") {
sendSurvey(ticket.customerId);
}
Integrates support across email, chat, and phone.
// Example: Route query regardless of channel
routeQuery(query);
Generates reports on support metrics.
// Example: Report average resolution time weekly
generateReport("resolutionTime", "weekly");
Expert systems enhance customer support efficiency and quality.
Predicts product demand to optimize stock levels.
// Example: Increase stock if demand predicted high
if (forecast.demand > stock.level) {
orderMoreStock();
}
Chooses suppliers based on criteria like cost and quality.
// Example: Select supplier with best rating
supplier = selectSupplier(criteria = {rating: "high", cost: "low"});
Keeps inventory at optimal levels to reduce costs.
// Example: Reduce inventory if turnover low
if (inventory.turnoverRate < threshold) {
reduceInventory();
}
Plans transportation routes for efficiency.
// Example: Choose shortest delivery route
route = planRoute(deliveryPoints, optimize="distance");
Monitors order status and updates customers.
// Example: Notify customer on shipment
if (order.status == "shipped") {
notifyCustomer(order.id, "Your order has shipped");
}
Identifies risks in the supply chain.
// Example: Alert if supplier delayed
if (supplier.deliveryDelay > threshold) {
alert("Supplier delay");
}
Monitors and reduces supply chain costs.
// Example: Suggest cheaper supplier options
if (currentSupplier.cost > budget) {
suggestAlternativeSuppliers();
}
Ensures supply chain meets regulations.
// Example: Check supplier certifications
if (!supplier.isCertified()) {
blockSupplier(supplier.id);
}
Monitors environmental impact of supply chain.
// Example: Prefer eco-friendly suppliers
if (supplier.ecoRating > threshold) {
prioritizeSupplier(supplier.id);
}
Expert systems optimize supply chain efficiency and reduce risks.
Monitors crop health using sensor data.
// Example: Alert if soil moisture too low
if (soil.moisture < threshold) {
alert("Irrigation needed");
}
Detects pest infestations early.
// Example: Detect pest presence from images
if (imageAnalysis.detect("pests")) {
alert("Pest infestation detected");
}
Optimizes watering schedules.
// Example: Schedule irrigation based on moisture and weather
if (soil.moisture < threshold && !forecast.rain) {
startIrrigation();
}
Recommends fertilizer types and amounts.
// Example: Apply fertilizer if nitrogen low
if (soil.nitrogen < threshold) {
applyFertilizer("Nitrogen", amount);
}
Suggests optimal harvest times for crops.
// Example: Harvest when crop moisture below target
if (crop.moisture < target) {
suggestHarvest();
}
Uses weather data to aid farm decisions.
// Example: Alert frost risk in next 24 hours
if (weather.forecast("frost")) {
alert("Frost warning");
}
Identifies crop diseases and suggests treatments.
// Example: Suggest treatment if blight detected
if (crop.hasDisease("blight")) {
recommendTreatment("fungicide");
}
Schedules maintenance for farm machinery.
// Example: Schedule tractor maintenance every 500 hours
if (equipment.hoursUsed > 500) {
scheduleMaintenance("tractor");
}
Analyzes commodity prices for selling decisions.
// Example: Suggest sell when price exceeds target
if (market.price > targetPrice) {
suggestSell();
}
Expert systems enhance farm productivity and decision-making.
Finds shortest or fastest routes.
// Example: Calculate route with minimal distance
route = calculateOptimalRoute(start, destination);
Monitors and manages traffic flow.
// Example: Adjust traffic lights based on congestion
if (trafficDensity > threshold) {
extendGreenLight();
}
Tracks and schedules vehicles in a fleet.
// Example: Schedule maintenance for truck fleet
if (truck.hoursDriven > maintenanceInterval) {
scheduleMaintenance(truck.id);
}
Identifies risky driving conditions.
// Example: Alert driver of slippery roads
if (weatherCondition == "rain" && roadCondition == "slippery") {
alertDriver("Drive carefully");
}
Optimizes public transport timetables.
// Example: Increase buses during rush hours
if (timeOfDay == "rush hour") {
increaseBusFrequency();
}
Monitors vehicle health and alerts on issues.
// Example: Alert if engine temperature too high
if (engine.temperature > safeLimit) {
alert("Engine overheating");
}
Optimizes fuel consumption.
// Example: Suggest route with best fuel efficiency
suggestRoute("fuel efficient");
Ensures vehicles meet legal requirements.
// Example: Check if driver hours comply with regulations
if (driver.hoursDriven > maxAllowed) {
notifyComplianceIssue();
}
Automates accident and incident reports.
// Example: Generate report after accident detected
if (accidentDetected) {
generateIncidentReport();
}
Expert systems improve safety and efficiency in transportation.
Analyzes legal documents for issues.
// Example: Flag contracts missing clauses
if (!contract.hasClause("arbitration")) {
flagDocument(contract.id);
}
Predicts outcomes based on precedent.
// Example: Predict case win if similar precedent
if (case.similarTo(precedent) && precedent.outcome == "win") {
predictOutcome("win");
}
Finds relevant laws and cases.
// Example: Search laws related to contract disputes
results = searchLegalDatabase("contract disputes");
Checks regulations adherence.
// Example: Verify company policies comply with regulations
if (!companyPolicies.complyWith(regulations)) {
alertComplianceIssue();
}
Assists in creating legal contracts.
// Example: Suggest standard clauses for NDA
contract.addClauses(standardNDAClauses);
Organizes evidence and case materials.
// Example: Categorize evidence by type
evidence.sortByType();
Provides automated initial consultations.
// Example: Ask client basic questions to gather facts
askClient("Describe the issue");
Automates invoicing and payment tracking.
// Example: Generate invoice after case closure
if (case.status == "closed") {
generateInvoice(client.id);
}
Analyzes data for trends and risks.
// Example: Analyze frequency of contract disputes
analyzeTrend("contract disputes");
Expert systems assist in streamlining legal work and improving accuracy.
Evaluates candidate resumes automatically.
// Example: Shortlist candidates with required skills
if (candidate.skills.containsAll(requiredSkills)) {
shortlist(candidate.id);
}
Analyzes employee performance metrics.
// Example: Flag employees with low productivity
if (employee.performanceScore < threshold) {
flagEmployee(employee.id);
}
Suggests courses based on skill gaps.
// Example: Recommend course if skill below level
if (employee.skillLevel("Java") < desiredLevel) {
recommendTraining("Java basics");
}
Tracks absenteeism and tardiness.
// Example: Alert if absences exceed limit
if (employee.absences > maxAllowed) {
sendWarning(employee.id);
}
Monitors engagement via surveys.
// Example: Suggest team building if engagement low
if (survey.engagementScore < threshold) {
suggestActivity("team building");
}
Automates salary calculation and deductions.
// Example: Calculate payroll including overtime
payroll = calculateSalary(employee.hoursWorked, overtime);
Ensures labor law compliance.
// Example: Check if working hours meet regulations
if (!employee.workingHours.compliesWithLaw()) {
notifyHR(employee.id);
}
Identifies candidates for key roles.
// Example: Mark potential successors for manager role
if (employee.potential > threshold) {
addToSuccessionPlan(employee.id, "manager");
}
Assists in resolving workplace conflicts.
// Example: Suggest mediation if conflict reported
if (conflict.reported) {
suggestMediation(conflict.parties);
}
Expert systems streamline HR processes and improve employee management.
Groups customers based on behavior and demographics.
// Example: Segment customers by purchase frequency
segments = segmentCustomers(customers, "purchaseFrequency");
Plans and tracks marketing campaigns.
// Example: Launch campaign targeting segment A
launchCampaign("SegmentA");
Ranks potential customers based on interest.
// Example: Score leads based on website interactions
leads.forEach(lead => {
lead.score = calculateLeadScore(lead);
});
Analyzes social media sentiment.
// Example: Analyze tweets mentioning brand
sentiment = analyzeSocialMedia("brandName");
Suggests products based on purchase history.
// Example: Recommend similar products
recommendations = recommendProducts(customer.purchaseHistory);
Adjusts pricing based on market conditions.
// Example: Reduce price if sales drop
if (sales < target) {
adjustPrice(product, -10);
}
Tracks competitor activities.
// Example: Monitor competitor pricing
competitorPrice = getCompetitorPrice(product);
Forecasts market changes.
// Example: Predict rising demand for product category
if (trendAnalysis("category") == "rising") {
increaseInventory("category");
}
Processes feedback to improve products.
// Example: Flag recurring complaints
complaints = analyzeFeedback(feedback);
if (complaints.contains("delivery delay")) {
alertProductTeam();
}
Expert systems help optimize marketing strategies and customer engagement.
Predicts energy demand for grid management.
// Example: Forecast peak load for next day
peakLoad = forecastLoad("nextDay");
Optimizes energy flow in the grid.
// Example: Allocate energy to high-demand areas
allocateEnergy(demandAreas);
Identifies faults in energy equipment.
// Example: Detect transformer failure signs
if (transformer.temperature > limit) {
alertFault("transformer");
}
Manages solar, wind, and other renewables.
// Example: Balance solar input with grid demand
balanceRenewable("solar");
Adjusts consumption based on supply.
// Example: Send incentives for off-peak usage
if (currentLoad > threshold) {
sendIncentives("offPeak");
}
Controls battery charge and discharge.
// Example: Charge batteries when supply high
if (supply > demand) {
chargeBattery();
}
Tracks pollution levels from energy sources.
// Example: Alert if emissions exceed limits
if (emissions > maxAllowed) {
triggerAlarm();
}
Minimizes energy costs.
// Example: Use cheaper energy sources during peak
switchEnergySource("cheapest");
Analyzes user energy consumption patterns.
// Example: Suggest energy-saving tips
if (userUsage > average) {
suggestTips();
}
Expert systems optimize energy usage and integrate renewables.
Monitors stock levels and sales rates.
// Example: Reorder product if stock low
if (product.stock < reorderLevel) {
reorderProduct(product.id);
}
Adjusts prices dynamically.
// Example: Increase price during high demand
if (demand > threshold) {
increasePrice(product.id);
}
Studies buying patterns.
// Example: Recommend products based on purchase history
recommendProducts(customer.history);
Coordinates suppliers and logistics.
// Example: Track deliveries and update stock
if (delivery.arrived) {
updateInventory(delivery.products);
}
Detects fraudulent transactions.
// Example: Flag suspicious returns
if (returns.frequency > limit) {
flagFraud(customer.id);
}
Automates query handling.
// Example: Respond to product availability queries
if (query.type == "availability") {
respond(product.stockStatus);
}
Targets customers with promotions.
// Example: Send promo to frequent buyers
if (customer.purchaseCount > 10) {
sendPromo(customer.id);
}
Plans product placement for sales.
// Example: Place popular items near entrance
arrangeStoreLayout(popularItems);
Predicts future sales.
// Example: Forecast monthly sales trends
forecast = salesForecast(monthlyData);
Expert systems improve retail efficiency and customer satisfaction.
Detects and diagnoses network issues.
// Example: Alert if link down
if (network.linkStatus == "down") {
alertNetworkTeam();
}
Optimizes routing for data packets.
// Example: Choose least congested path
route = choosePath("leastCongestion");
Distributes bandwidth efficiently.
// Example: Allocate more bandwidth during peak hours
if (time.isPeak()) {
allocateBandwidth(highPriorityUsers);
}
Automates support via chatbots.
// Example: Answer common billing queries
if (query.type == "billing") {
respondBillingFAQs();
}
Identifies fraudulent calls or access.
// Example: Flag suspicious call patterns
if (call.pattern == "suspicious") {
flagAccount();
}
Automates service activation and changes.
// Example: Activate new plan on request
if (request.type == "activate plan") {
activatePlan(request.planId);
}
Calculates and issues bills.
// Example: Generate monthly invoice
generateInvoice(customer.id);
Tracks network performance metrics.
// Example: Alert if latency exceeds limit
if (latency > threshold) {
alertNetwork();
}
Ensures telecom operations meet regulations.
// Example: Audit call records
auditRecords();
Expert systems improve telecom reliability and customer experience.
Tracks pollution levels in air and water.
// Example: Alert if pollution exceeds safe levels
if (pollution.level > safeLimit) {
alert("Pollution alert");
}
Optimizes waste collection and recycling.
// Example: Schedule pickup when bins full
if (bin.fillLevel > 90%) {
schedulePickup(bin.id);
}
Recommends ways to save water and energy.
// Example: Suggest reduce water usage during drought
if (droughtCondition) {
suggestAction("reduce water usage");
}
Evaluates effects of projects on environment.
// Example: Assess impact of new construction
impact = assessImpact(constructionProject);
Simulates climate change scenarios.
// Example: Model temperature rise over 50 years
model = simulateClimateChange(50);
Predicts and manages natural disasters.
// Example: Alert for flood risk after heavy rain
if (rainfall > threshold) {
alert("Flood risk");
}
Tracks species populations and habitats.
// Example: Report endangered species sightings
reportSighting(species);
Ensures environmental laws are followed.
// Example: Check factory emissions compliance
if (!factory.emissionsCompliant()) {
issueFine(factory.id);
}
Educates public on environmental issues.
// Example: Send tips for recycling
sendMessage(publicList, "Recycle tips");
Expert systems support sustainable environmental management.
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);
}
Identifies unusual transactions that might indicate fraud.
// Example: Flag transaction if amount unusually high
if (transaction.amount > 10000 && !transaction.isVerified) {
flagFraud(transaction.id);
}
Helps manage investment portfolios by balancing risk and returns.
// Example: Rebalance portfolio if risk exceeds limit
if (portfolio.risk > acceptableRisk) {
rebalancePortfolio(portfolio.id);
}
Analyzes market trends to guide investment decisions.
// Example: Suggest buy if stock trend is upward
if (stock.trend == "upward") {
suggestBuy(stock.symbol);
}
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);
}
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);
}
Ensures all transactions and reports meet tax regulations.
// Example: Verify tax report completeness
if (taxReport.isComplete()) {
submitReport();
} else {
requestMoreInfo();
}
Helps individuals or companies plan budgets effectively.
// Example: Alert if expenses exceed budget
if (expenses > budget) {
alertUser("Budget exceeded");
}
Tracks repayments and sends reminders for overdue payments.
// Example: Send reminder if payment overdue
if (payment.dueDate < today && !payment.isPaid) {
sendReminder(applicant.id);
}
Expert systems in finance improve decision-making, reduce fraud, and enhance compliance.
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");
}
Recommends treatments based on diagnosis and patient history.
// Example: Recommend medication based on diagnosis
if (diagnosis == "flu") {
recommendTreatment("antiviral drugs");
}
Tracks vital signs and alerts for abnormalities.
// Example: Alert if heart rate too high
if (patient.heartRate > 100) {
alertMedicalStaff(patient.id);
}
Checks for harmful interactions between prescribed drugs.
// Example: Warn if two drugs have negative interaction
if (drugA.interactsWith(drugB)) {
alertDoctor();
}
Assists in interpreting X-rays, MRIs, and other images.
// Example: Detect abnormality in X-ray image
if (imageAnalysis.detects("tumor")) {
flagForReview();
}
Optimizes scheduling to reduce patient wait times.
// Example: Schedule appointment when doctor is free
if (doctor.isAvailable(timeSlot)) {
bookAppointment(patient.id, timeSlot);
}
Automates billing and claims processing.
// Example: Generate invoice after treatment
generateInvoice(patient.id);
Maintains and secures patient medical records.
// Example: Update patient record with new test results
updateRecord(patient.id, testResults);
Suggests screenings or lifestyle changes to prevent disease.
// Example: Recommend flu shot before winter
if (season == "fall") {
recommend("flu vaccination");
}
Expert systems improve patient care, diagnosis, and healthcare efficiency.
Monitors and adjusts production lines for efficiency.
// Example: Pause line if defect rate too high
if (defectRate > 5%) {
pauseProductionLine();
}
Schedules preventive maintenance to reduce downtime.
// Example: Schedule maintenance after 1000 hours of use
if (equipment.hoursUsed >= 1000) {
scheduleMaintenance(equipment.id);
}
Checks product quality against standards.
// Example: Reject batch if quality below threshold
if (batch.qualityScore < 90) {
rejectBatch(batch.id);
}
Manages raw materials and finished goods stock.
// Example: Reorder raw materials if below minimum
if (rawMaterial.stock < minimumStock) {
placeOrder(rawMaterial.id);
}
Analyzes production processes to improve efficiency.
// Example: Adjust process parameters to reduce waste
adjustParameters({temperature: optimalTemp, speed: optimalSpeed});
Detects unsafe conditions and alerts workers.
// Example: Alert if toxic gas detected
if (gasSensor.level > safeLimit) {
alertWorkers();
}
Monitors and reduces energy usage.
// Example: Turn off machines during breaks
if (breakTime) {
shutdownMachines();
}
Plans production to meet demand efficiently.
// Example: Schedule jobs based on priority
scheduleJobs(jobs, priorityCriteria);
Identifies and minimizes material waste.
// Example: Reduce scrap by adjusting cutting patterns
adjustCuttingPatterns();
Expert systems optimize manufacturing processes and improve safety.
Uses chatbots to answer common customer questions automatically.
// Example: Respond with FAQ answer
if (query.type == "FAQ") {
respondWithFAQ(query);
}
Prioritizes and routes customer complaints for faster resolution.
// Example: Route urgent complaints to senior staff
if (complaint.priority == "high") {
routeToStaff("senior");
}
Analyzes customer feedback to identify improvement areas.
// Example: Flag recurring complaint topics
topics = analyzeFeedback(feedback);
if (topics.contains("delivery delay")) {
alertManagement();
}
Customizes responses based on customer profile and history.
// Example: Greet returning customer by name
if (customer.isReturning) {
greetCustomer(customer.name);
}
Predicts potential customer issues to proactively address them.
// Example: Notify customer of possible service outage
if (system.status == "unstable") {
notifyCustomers("Possible outage");
}
Keeps FAQs and help articles up to date.
// Example: Update knowledge base with new solutions
updateKnowledgeBase(newSolutions);
Automatically escalates unresolved issues.
// Example: Escalate if issue unresolved after 24 hours
if (issue.unresolvedDuration > 24) {
escalateIssue(issue.id);
}
Monitors satisfaction scores and triggers actions if low.
// Example: Send survey if satisfaction below threshold
if (survey.score < 3) {
sendFollowUpSurvey(customer.id);
}
Provides training material to customer service agents.
// Example: Recommend training for agents on new product
if (product.updated) {
assignTraining("new product");
}
Expert systems enhance customer service efficiency and satisfaction.
Calculates the best routes to reduce travel time and cost.
// Example: Choose shortest path avoiding traffic
route = findOptimalRoute(start, destination, trafficData);
Tracks vehicles and schedules maintenance.
// Example: Alert for vehicle maintenance due
if (vehicle.mileage > maintenanceThreshold) {
scheduleMaintenance(vehicle.id);
}
Monitors traffic flow and adjusts signals accordingly.
// Example: Change signal timing based on congestion
if (trafficDensity > threshold) {
adjustSignalTiming();
}
Provides real-time alerts and recommendations to drivers.
// Example: Warn driver about sharp turn ahead
if (upcomingTurn.sharpness > limit) {
alertDriver("Sharp turn ahead");
}
Detects accidents and alerts emergency services.
// Example: Send alert if sudden stop detected
if (vehicle.acceleration < suddenStopThreshold) {
notifyEmergencyServices(vehicle.location);
}
Optimizes bus and train schedules based on demand.
// Example: Add extra bus during peak hours
if (passengerCount > peakThreshold) {
deployAdditionalBus(route.id);
}
Monitors shipment status and location.
// Example: Update cargo status in real-time
updateCargoStatus(cargo.id, currentLocation);
Monitors vehicle emissions and suggests actions.
// Example: Alert driver to reduce idling
if (engine.idleTime > limit) {
alertDriver("Reduce engine idling");
}
Ensures vehicles and drivers meet safety regulations.
// Example: Verify driver license validity
if (!driver.license.isValid()) {
restrictVehicleAccess(driver.id);
}
Expert systems in transportation improve safety, efficiency, and environmental impact.
DRF is a powerful toolkit to build Web APIs easily with Django, supporting serialization, authentication, and more.
pip install djangorestframework
# settings.py
INSTALLED_APPS = [
# other apps
'rest_framework',
]
from rest_framework import serializers
from myapp.models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
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)
# urls.py
from django.urls import path
from .views import ItemList
urlpatterns = [
path('api/items/', ItemList.as_view(), name='item-list'),
]
Serializer defines fields manually; ModelSerializer auto-generates fields from model.
from rest_framework import serializers
class CustomSerializer(serializers.Serializer):
name = serializers.CharField(max_length=100)
age = serializers.IntegerField()
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
class BookSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True)
class Meta:
model = Book
fields = ['title', 'author']
Support complex data by nesting serializers.
class ItemSerializer(serializers.ModelSerializer):
is_expensive = serializers.SerializerMethodField()
def get_is_expensive(self, obj):
return obj.price > 100
Viewsets combine logic for multiple views into one class, reducing code duplication.
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
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)),
]
Automatically provide CRUD endpoints with less code.
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'})
DRF provides TokenAuthentication, SessionAuthentication, BasicAuthentication.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
Control who can access APIs, e.g. IsAuthenticated, AllowAny, IsAdminUser.
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!'})
from rest_framework.permissions import BasePermission
class IsOwner(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
# Install
pip install djangorestframework-simplejwt
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
Break large result sets into pages to improve performance and UX.
PageNumberPagination, LimitOffsetPagination, CursorPagination.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
Install django-filter
to add filtering capabilities.
pip install django-filter
# settings.py
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
}
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']
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
Throttling limits the rate of requests to prevent abuse and ensure fair resource usage.
Includes AnonRateThrottle, UserRateThrottle, ScopedRateThrottle.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day',
}
}
from rest_framework.throttling import SimpleRateThrottle
class CustomIPThrottle(SimpleRateThrottle):
scope = 'custom'
def get_cache_key(self, request, view):
return self.get_ident(request)
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'})
Django REST Framework returns HTTP 429 when throttled.
Ensures reliability, correctness, and regression prevention for your API endpoints.
from rest_framework.test import APIClient
client = APIClient()
response = client.get('/api/items/')
print(response.status_code)
print(response.data)
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)
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)
self.client.force_authenticate(user=self.user)
response = self.client.get(url)
To tailor API responses to your clients’ needs with custom page sizes, formats, or metadata.
from rest_framework.pagination import PageNumberPagination
class CustomPagination(PageNumberPagination):
page_size = 5
page_size_query_param = 'page_size'
max_page_size = 20
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
Paginated responses include keys like count
, next
, previous
, and results
.
from rest_framework.pagination import LimitOffsetPagination
class LimitOffsetPaginationCustom(LimitOffsetPagination):
default_limit = 10
max_limit = 50
Use different throttling rates per view using scopes.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.ScopedRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'user': '1000/day',
'anon': '100/day',
'custom_scope': '10/minute',
}
}
from rest_framework.views import APIView
class CustomThrottleView(APIView):
throttle_scope = 'custom_scope'
def get(self, request):
return Response({'message': 'Scoped throttle applied'})
DRF checks all throttles; if any fails, request is blocked.
Implement logging in custom throttle classes for audit.
Maintain backward compatibility while evolving APIs.
URL path versioning, query parameter versioning, header versioning.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
}
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})
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'),
]
Route requests to different serializers or logic based on version.