1. Install Django
pip install django
2. Create a New Django Project
django-admin startproject myproject
3. Create a New Django App
python manage.py startapp myapp
4. Run the Django Development Server
python manage.py runserver
5. Create a New Django Model
# models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=255)
age = models.IntegerField()
6. Create a New Django View
# views.py
from django.shortcuts import render
from .models import MyModel
def my_view(request):
my_objects = MyModel.objects.all()
return render(request, 'my_template.html', {'my_objects': my_objects})
7. Create a New Django Template
<!-- my_template.html -->
<h1>My Template</h1>
<ul>
{% for obj in my_objects %}
<li>{{ obj.name }} ({{ obj.age }})</li>
{% endfor %}
</ul>
8. Create a New Django URL Pattern
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.my_view, name='my_view'),
]
9. Use Django's ORM to Query the Database
# views.py
from django.shortcuts import render
from .models import MyModel
def my_view(request):
my_objects = MyModel.objects.all()
return render(request, 'my_template.html', {'my_objects': my_objects})
10. Use Django's Forms to Handle User Input
# forms.py
from django import forms
from .models import MyModel
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('name', 'age')
11. Use Django's Authentication System
# views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
def my_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('my_view')
return render(request, 'my_template.html')
12. Use Django's Authorization System
# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import permission_required
@permission_required('myapp.can_view_my_model')
def my_view(request):
my_objects = MyModel.objects.all()
return render(request, 'my_template.html', {'my_objects': my_objects})
13. Use Django's Signals to Handle Events
# models.py
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, created, **kwargs):
if created:
print(f"New {sender.__name__} created: {instance.name}")
14. Use Django's Middleware to Modify Requests and Responses
# middleware.py
from django.http import HttpResponse
class MyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response['X-My-Header'] = 'My Value'
return response
15. Use Django's Cache Framework to Improve Performance
# settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
16. Use Django's Internationalization and Localization Features
# settings.py
USE_I18N = True
USE_L10N = True
17. Use Django's File Upload Handling
# models.py
from django.db import models
class My Model(models.Model):
name = models.CharField(max_length=255)
file = models.FileField(upload_to='uploads/')
<h2>18. Use Django's Static Files Handling</h2>
<pre>
<code>
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
19. Use Django's Media Files Handling
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
20. Use Django's Admin Interface
# admin.py
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
21. Use Django's Custom User Model
# models.py
from django.contrib.auth.models import AbstractUser
class CustomUser (AbstractUser ):
pass
22. Use Django's Class-Based Views
# views.py
from django.views import View
from django.shortcuts import render
class MyView(View):
def get(self, request):
return render(request, 'my_template.html')
23. Use Django's Generic Views
# views.py
from django.views.generic import ListView
from .models import MyModel
class MyModelListView(ListView):
model = MyModel
template_name = 'my_template.html'
24. Use Django's Template Inheritance
<!-- base.html -->
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>
<!-- my_template.html -->
{% extends "base.html" %}
{% block content %}
<h1>My Template</h1>
{% endblock %}
25. Use Django's URL Reversing
# views.py
from django.urls import reverse
def my_view(request):
url = reverse('my_view')
return redirect(url)
26. Use Django's Session Framework
# views.py
def my_view(request):
request.session['my_key'] = 'my_value'
return render(request, 'my_template.html')
27. Use Django's CSRF Protection
<!-- my_template.html -->
<form method="post">
{% csrf_token %}
<input type="submit">
</form>
28. Use Django's Pagination
# views.py
from django.core.paginator import Paginator
def my_view(request):
object_list = MyModel.objects.all()
paginator = Paginator(object_list, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'my_template.html', {'page_obj': page_obj})
29. Use Django's Testing Framework
# tests.py
from django.test import TestCase
class MyModelTest(TestCase):
def test_creation(self):
obj = MyModel.objects.create(name='Test', age=30)
self.assertEqual(obj.name, 'Test')
30. Use Django's Signals for Custom Actions
# models.py
from django.db.models.signals import pre_save
from django.dispatch import receiver
@receiver(pre_save, sender=MyModel)
def my_handler(sender, instance, **kwargs):
print(f"About to save {instance.name}")
31. Use Django's Custom Management Commands
# management/commands/my_command.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **kwargs):
self.stdout.write("Hello, World!")
32. Use Django's Middleware for Custom Processing
# middleware.py
class MyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
33. Use Django's Custom Template Tags
# templatetags/my_tags.py
from django import template
register = template.Library()
@register.simple_tag
def my_tag():
return "Hello, World!"
34. Use Django's Custom Template Filters
# templatetags/my_filters.py
from django import template
register = template.Library()
@register.filter
def my_filter(value):
return value.upper()
35. Use Django's Context Processors
# context_processors.py
def my_context_processor(request):
return {'my_variable': 'Hello, World!'}
36. Use Django's Static Files in Templates
<!-- my_template.html -->
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
37. Use Django's Media Files in Templates
<!-- my_template.html -->
<img src="{{ my_object.file.url }}" alt="My File">
38. Use Django's Custom User Authentication
# views.py
from django.contrib.auth import login, authenticate
def my_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
39. Use Django's Admin Customization
# admin.py
from django.contrib import admin
from .models import MyModel
class MyModelAdmin(admin.ModelAdmin):
list_display = ('name', 'age')
admin.site.register(MyModel, MyModelAdmin)
40. Use Django's URL Namespacing
# urls.py
app_name = 'myapp'
urlpatterns = [
path('', views.my_view, name='my_view'),
]
41. Use Django's Model Inheritance
# models.py
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class MyModel(BaseModel):
name = models.CharField(max_length=255)
42. Use Django's QuerySet Methods
# views.py
my_objects = MyModel.objects.filter(age__gte=18).order_by('name')
43. Use Django's Raw SQL Queries
# views.py
my_objects = MyModel.objects.raw('SELECT * FROM myapp_mymodel WHERE age > %s', [18])
44. Use Django's Transactions
# views.py
from django.db import transaction
@transaction.atomic
def my_view(request):
# Your code here
45. Use Django's Custom Validators
# validators.py
from django.core.exceptions import ValidationError
def validate_even(value):
if value % 2 != 0:
raise ValidationError(f'{value} is not an even number.')
46. Use Django's Model Managers
# models.py
class MyModelManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(active=True)
class MyModel(models.Model):
objects = MyModelManager()
47. Use Django's Custom QuerySet
# models.py
class MyModelQuerySet(models.QuerySet):
def active(self):
return self.filter(active=True)
class MyModel(models.Model):
objects = MyModelQuerySet.as_manager()
48. Use Django's Signals for Post-Delete Actions
# models.py
from django.db.models.signals import post_delete
@receiver(post_delete, sender=MyModel)
def my_handler(sender, instance, **kwargs):
print(f"{instance.name} was deleted.")
49. Use Django's Custom Admin Actions
# admin.py
def my_custom_action(modeladmin, request, queryset):
queryset.update(active=False)
class MyModelAdmin(admin.ModelAdmin):
actions = [my_custom_action]
50. Use Django's Custom Template Context
# views.py
def my_view(request):
context = {'my_variable': 'Hello, World!'}
return render(request, 'my_template.html', context)
51. Use Django's Formsets
# views.py
from django.forms import formset_factory
MyFormSet = formset_factory(MyForm)
def my_view(request):
formset = MyFormSet(request.POST or None)
return render(request, 'my_template.html', {'formset': formset})
52. Use Django's ModelForm for Form Handling
# views.py
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
form = MyForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'my_template.html', {'form': form})
53. Use Django's Custom Template Tags for Logic
# templatetags/my_tags.py
from django import template
register = template.Library()
@register.simple_tag
def multiply(x, y):
return x * y
54. Use Django's Custom Template Filters for Data Manipulation
# templatetags/my_filters.py
from django import template
register = template.Library()
@register.filter
def add(value, arg):
return value + arg
55. Use Django's Class-Based Views for CRUD Operations
# views.py
from django.views.generic import CreateView, UpdateView, DeleteView
from .models import MyModel
class MyModelCreateView(CreateView):
model = MyModel
fields = ['name', 'age']
template_name = 'my_template.html'
56. Use Django's URL Dispatcher for Clean URLs
# urls.py
from django.urls import path
from .views import MyModelCreateView
urlpatterns = [
path('create/', MyModelCreateView.as_view(), name='create'),
]
57. Use Django's Admin Filters
# admin.py
class MyModelAdmin(admin.ModelAdmin):
list_filter = ('age',)
58. Use Django's Admin Search
# admin.py
class MyModelAdmin(admin.ModelAdmin):
search_fields = ('name',)
59. Use Django's Admin List Display
# admin.py
class MyModelAdmin(admin.ModelAdmin):
list_display = ('name', 'age', 'created_at')
60. Use Django's Admin Read-Only Fields
# admin.py
class MyModelAdmin(admin.ModelAdmin):
readonly_fields = ('created_at',)
61. Use Django's Admin Inline Models
# admin.py
class MyInline(admin.TabularInline):
model = MyModel
class MyParentAdmin(admin.ModelAdmin):
inlines = [MyInline]
62. Use Django's Custom Admin Templates
# admin.py
class MyModelAdmin(admin.ModelAdmin):
change_form_template = 'admin/my_change_form.html'
63. Use Django's Custom Error Pages
# views.py
def handler404(request, exception):
return render(request, '404.html', status=404)
64. Use Django's Custom Middleware for Request Logging
# middleware.py
class RequestLoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(f"Request: {request.path}")
return self.get_response(request)
65. Use Django's Custom User Authentication Backend
# backends.py
from django.contrib.auth.backends import ModelBackend
class CustomBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
# Custom authentication logic
pass
66. Use Django's Custom User Registration
# views.py
def register(request):
if request.method == 'POST':
# Handle registration
pass
return render(request, 'registration.html')
67. Use Django's Custom User Profile
# models.py
from django.conf import settings
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
bio = models.TextField()
68. Use Django's Custom User Permissions
# models.py
class MyModel(models.Model):
class Meta:
permissions = [
("can_view_mymodel", "Can view MyModel"),
]
69. Use Django's Custom User Groups
# views.py
from django.contrib.auth.models import Group
def create_group(request):
group, created = Group.objects.get_or_create(name='MyGroup')
70. Use Django's Custom User Roles
# views.py
def assign_role(request, user_id):
user = User.objects.get(id=user_id)
group = Group.objects.get(name='MyGroup')
user.groups.add(group)
71. Use Django's Custom User Login
# views.py
from django.contrib.auth import login
def custom_login(request):
if request.method == 'POST':
# Handle login
login(request, user)
72. Use Django's Custom User Logout
# views.py
from django.contrib.auth import logout
def custom_logout(request):
logout(request)
73. Use Django's Custom User Password Reset
# views.py
from django.contrib.auth.views import PasswordResetView
class CustomPasswordResetView(PasswordResetView):
template_name = 'password_reset.html'
74. Use Django's Custom User Password Change
# views.py
from django.contrib.auth.views import PasswordChangeView
class CustomPasswordChangeView(PasswordChangeView):
template_name = 'password_change.html'
75. Use Django's Custom User Profile View
# views.py
def profile_view(request):
return render(request, 'profile.html', {'user': request.user})
76. Use Django's Custom User Profile Update
# views.py
def update_profile(request):
if request.method == 'POST':
# Handle profile update
pass
77. Use Django's Custom User Profile Delete
# views.py
def delete_profile(request):
request.user.delete()
return redirect('home')
78. Use Django's Custom User Profile Picture Upload
# models.py
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='profile_pics/')
79. Use Django's Custom User Profile Picture Display
<img src="{{ user.userprofile.profile_picture.url }}" alt="Profile Picture">
80. Use Django's Custom User Profile Bio Update
# views.py
def update_bio(request):
if request.method == 'POST':
# Handle bio update
pass
81. Use Django's Custom User Profile Bio Display
<!-- profile.html -->
<p>{{ user.userprofile.bio }}</p>
82. Use Django's Custom User Profile Settings
# views.py
def settings_view(request):
return render(request, 'settings.html')
83. Use Django's Custom User Notifications
# models.py
class Notification(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
message = models.TextField()
is_read = models.BooleanField(default=False)
84. Use Django's Custom User Notification Display
# views.py
def notifications_view(request):
notifications = Notification.objects.filter(user=request.user)
return render(request, 'notifications.html', {'notifications': notifications})
85. Use Django's Custom User Notification Mark as Read
# views.py
def mark_as_read(request, notification_id):
notification = Notification.objects.get(id=notification_id)
notification.is_read = True
notification.save()
86. Use Django's Custom User Notification Delete
# views.py
def delete_notification(request, notification_id):
notification = Notification.objects.get(id=notification_id)
notification.delete()
87. Use Django's Custom User Activity Log
# models.py
class ActivityLog(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
action = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
88. Use Django's Custom User Activity Log Display
# views.py
def activity_log_view(request):
logs = ActivityLog.objects.filter(user=request.user)
return render(request, 'activity_log.html', {'logs': logs})
89. Use Django's Custom User Activity Log Delete
# views.py
def delete_activity_log(request, log_id):
log = ActivityLog.objects.get(id=log_id)
log.delete()
90. Use Django's Custom User Activity Log Filter
# views.py
def filter_activity_log(request):
logs = ActivityLog.objects.filter(user=request.user).order_by('-timestamp')
return render(request, 'activity_log.html', {'logs': logs})
91. Use Django's Custom User Activity Log Search
# views.py
def search_activity_log(request):
query = request.GET.get('q')
logs = ActivityLog.objects.filter(user=request.user, action__icontains=query)
return render(request, 'activity_log.html', {'logs': logs})
92. Use Django's Custom User Activity Log Pagination
# views.py
from django.core.paginator import Paginator
def paginated_activity_log_view(request):
logs = ActivityLog.objects.filter(user=request.user)
paginator = Paginator(logs, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'activity_log.html', {'page_obj': page_obj})
93. Use Django's Custom User Activity Log Export
# views.py
import csv
from django.http import HttpResponse
def export_activity_log(request):
logs = ActivityLog.objects.filter(user=request.user)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="activity_log.csv"'
writer = csv.writer(response)
writer.writerow(['Action', 'Timestamp'])
for log in logs:
writer.writerow([log.action, log.timestamp])
return response
94. Use Django's Custom User Activity Log Import
# views.py
def import_activity_log(request):
if request.method == 'POST':
file = request.FILES['file']
# Handle file import logic
return render(request, 'import_activity_log.html')
95. Use Django's Custom User Activity Log Notification
# views.py
def notify_user_activity(request):
# Logic to notify user about their activity
pass
96. Use Django's Custom User Activity Log WebSocket Integration
# views.py
def websocket_activity_log_view(request):
# Logic for WebSocket integration
pass
97. Use Django's Custom User Activity Log API Integration
# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def api_activity_log_view(request):
logs = ActivityLog.objects.filter(user=request.user)
return Response({'logs': [{'action': log.action, 'timestamp': log.timestamp} for log in logs]})
98. Use Django's Custom User Activity Log Frontend Framework Integration
# views.py
def frontend_activity_log_view(request):
# Logic to integrate with a frontend framework
pass
99. Use Django's Custom User Activity Log Analytics
# views.py
def analytics_activity_log_view(request):
# Logic to analyze user activity logs
pass
100. Use Django's Custom User Activity Log Reporting
# views.py
def report_activity_log_view(request):
# Logic to generate reports from activity logs
pass