Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Create and Use Signals in Django?
Django signals allow you to trigger specific functions automatically when certain events occur in your application. For example, you can send a confirmation email when a new user registers, or log changes when database objects are modified.
Types of Django Signals
Django provides three main types of signals ?
pre_save/post_save ? Triggered when an object is saved to the database
pre_delete/post_delete ? Triggered when an object is deleted from the database
pre_init/post_init ? Triggered when a new model instance is created
Creating a Django Project with Signals
Let's build a complete example that demonstrates Django signals in action.
Step 1: Project Setup
Install Django and create a new project ?
pip install Django django-admin startproject django_demo cd django_demo python manage.py startapp firstApp
Step 2: Configure URLs
Create urls.py in the firstApp directory ?
from django.urls import path
from . import views
urlpatterns = [
path('', views.create_user, name='create_user'),
]
Update the main urls.py file in django_demo ?
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("firstApp.urls")),
]
Step 3: Register the App
Add the app to INSTALLED_APPS in settings.py ?
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'firstApp',
]
Step 4: Create the Model
Define a User model in models.py ?
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
def __str__(self):
return self.name
Run migrations to create the database table ?
python manage.py makemigrations python manage.py migrate
Creating and Connecting Signals
Step 5: Define the Signal Handler
Create signals.py in the firstApp directory ?
from django.db.models.signals import post_save
from django.dispatch import receiver
from firstApp.models import User
@receiver(post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
if created:
print('A new user was created:', instance.name, instance.email)
The @receiver decorator connects the function to the post_save signal. The created parameter is True when a new object is created and False when an existing object is updated.
Step 6: Register the Signals
Update apps.py to import signals when the app is ready ?
from django.apps import AppConfig
class FirstappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'firstApp'
def ready(self):
import firstApp.signals
Creating the User Interface
Step 7: Create the Form
Create forms.py to handle user input ?
from django import forms
from firstApp.models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('name', 'email')
Step 8: Create the View
Add the view function in views.py ?
from django.shortcuts import render, redirect
from firstApp.forms import UserForm
def create_user(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
return redirect('create_user')
else:
form = UserForm()
return render(request, 'base.html', {'form': form})
Step 9: Configure Templates
Update TEMPLATES in settings.py ?
import os
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'firstApp', 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
}]
Create the template file firstApp/templates/base.html ?
<!DOCTYPE html>
<html>
<head>
<title>Django Signals Demo</title>
</head>
<body>
<h1>Create a New User</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create User">
</form>
</body>
</html>
Testing the Application
Run the development server ?
python manage.py runserver
When you visit http://127.0.0.1:8000 and submit the form, you'll see the signal handler print the user information in the console. This demonstrates that the signal was triggered successfully when the new user was saved to the database.
Signal Handler Parameters
Signal handlers receive several useful parameters ?
sender ? The model class that sent the signal
instance ? The actual instance being saved
created ? Boolean indicating if this is a new record
**kwargs ? Additional keyword arguments
Common Use Cases
Django signals are commonly used for ?
Sending confirmation emails when users register
Creating user profiles automatically
Logging database changes for auditing
Clearing caches when data is updated
Triggering notifications or webhooks
Conclusion
Django signals provide a powerful way to decouple your application logic by automatically triggering functions when specific events occur. Use the @receiver decorator to connect signal handlers, and remember to import your signals in the app's ready() method to ensure they're properly registered.
