How to Create and Use Signals in Django?


Django is a Python web framework developer used to develop web applications faster and write down easy code syntax. Also, Django is a full feature rich application as it contains many features, including the Django signals.

In Django, signals are used to trigger some function whenever any event occurs. For example, when users make some changes in the database, we can trigger a particular function, which can show the changes to users on the web page.

The Django contains a total of 3 types of signals which we have explained below.

  • Pre_save/post_save − It triggers the action whenever a user saves any object in the database.

  • Pre_delete/post_delete − It automatically gets triggered whenever users want to delete an object from the database.

  • Pre_init/post_init − It gets fired whenever a new model is created in the database.

In this tutorial, we will learn to use the signals in Django. Here, we will create an app from scratch and add a code to create a signal.

Users should follow the steps below to create signals in the Django app.

  • Step 1 − First, install Django on your local computer by running the below command in the terminal if it’s already not installed.

pip install Django
  • Step 2 − Now, run the below command in the terminal to create new Django project.

django-admin startproject django_demo
  • Step 3 − After that, run the below command in the terminal to change the directory in the terminal and create a new app called the ‘firstApp’.

cd django_demo
python manage.py startapp firstApp
  • Step 4 − Next, we require creating a urls.py file inside the ‘firstApp’ folder and add the below code in the file.

from django.urls import path
from . import views
urlpatterns = [
   path('', views.create_user)
]
  • Step 5 − Also, we require to set up the urls.py file of the django project. Open the urls.py file located inside the django_demo folder, and add the below code into the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
   path('admin/', admin.site.urls),
   # here, firstApp is a app name
   path('', include("firstApp.urls")),
]

In the above code, we have included the URLs of the ‘firstApp’.

  • Step 6 − Now, we require to add the ‘firstApp’ inside the settings.py file of the django_demo folder. Open the settings.py file, and replace the current code with the below code.

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'firstApp',
]

In the above code, we have added the ‘firstApp’ inside the INSALLED_APPS array.

  • Step 7 − Now, we will create a model to save the user’s data in the database. Open the models.py file inside the ‘firstApp’ directory and add the below code into that.

from django.db import models

class User(models.Model):
   # Adding the name
   name = models.CharField(max_length=100)
   # Adding the email
   email = models.EmailField()

   def __str__(self):
      return self.name

In the above code, we have created the ‘User’ model containing the name and email field.

After that, run below both commands in the terminal one by one to migrate the database.

python manage.py makemigrations
python manage.py migrate
  • Step 8 − Now, create a ‘signals.py’ file inside the ‘firstApp’ directory, and add the code below to create a signal.

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)

In the above code, we have used the ‘post_save’ signal with the ‘User’ model. So, whenever a new user is saved in the database, it will call the user_created() function. On successfully creating a user, it prints the user’s name and email on the console.

  • Step 9 − Also, we require to register the signals in the app.py file. Open the app.py file and add the below code into the file.

from django.apps import AppConfig

class FirstappConfig(AppConfig):
   default_auto_field = 'django.db.models.BigAutoField'
   name = 'firstApp'

   def ready(self):
      import firstApp.signals
  • Step 10 − Next, let’s create a form to take user input. Create a forms.py file in the ‘firstApp’ directory and add the below code in the file.

from django import forms
from firstApp.models import User

class UserForm(forms.ModelForm):
   class Meta:
      model = User
      fields = ('name', 'email')

In the above code, we have imported the User model and created the UserForm class.

  • Step 11 − Next, let’s create a create_user view in the views.py file to handle the form submission. Open the views.py file and add below code in the file.

from django.shortcuts import render
from firstApp.forms import UserForm

def create_user(request):
   # If the form is submitted, save the user. Otherwise, just create an empty form.
   if request.method == 'POST':
      form = UserForm(request.POST)
      if form.is_valid():
         form.save()
   else:
      form = UserForm()
      # send the base.html file on the response.
   return render(request, 'base.html', {'form': form})

In the above code, we check if the method is POST and save the form if all form parameters are valid. Otherwise, we show the form to the users without saving the data of the form. Also, we render the ‘base.html’ template to the users.

  • Step 12 − Now, we require to create the ‘base.html’ template. Before that, create a ‘templates’ directory in the ‘firstApp’ folder. After that, open the ‘settings.py’ file, and add the below code instead of old code.

TEMPLATES = [{
      'BACKEND': 'django.template.backends.django.DjangoTemplates',
      'DIRS': [os.path.join(BASE_DIR, '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',
         ],
      },
   },
]

In the above code, we have added the path of the ‘templates’ directory as a value of the ‘DIRS’ property.

  • Step 13 − Next, create a base.html file inside the ‘templates’ directory, and add below code in the file.

<!DOCTYPE html>
<html>
<head>
   <title> Basic form </title>
</head>
<body>
   <h1>Create a new user</h1>
   <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="Create">
   </form>
</body>
</html>

The above code will show the form on the web page.

  • Step 14 − As a last step, you require to run the project by executing the below command in the project directory, which contains the manage.py file.

python manage.py runserver

Output

Users will see the below web page when they open the localhost.

Once you enter your name and email in the form and press the create button, it will invoke the create_user() function of the views.py file, saving data in the database. After saving data in the database, the signal will call the user_created() function, which prints the name and email in the console, as shown below.

Conclusion

We learned how the signal is used to trigger particular actions whenever any event gets fired. In real-time development, we can use signals to call the functions that send the confirmation email to users whenever a new user is created. Also, there are lots of other use cases of django signals.

Updated on: 11-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements