Django Signals and Receivers

 In my recent application with Django, I have happened to work with Django signals and receivers.

When developing software applications using object oriented programming architecture it is always a goal to develop loosely coupled, Maintainable, Testable and Extensible software

Have you ever asked yourself the best and easy way to archive loosely coupling in Django Python. Django signals is an optimal way to archive this.

Django includes a "signal dispatcher" which helps decoupled application get notified when action occur elsewhere in framework.

Signals allows certain sender to notify a set of receivers that action has taken place.

In this case am using sample codes of my Django application. I used Django signals to continuously update another data model and perform some maths behind the scenes

To get Started with signals Create signals.py file .

from django.db import models

from django.db.models.signals import post_save

from django.dispatch import receiver

from .models import DailyWork




@receiver(post_save, sender=DailyWork)

def update_total_income(sender, instance, created, **kwargs):

    if created:

        employee = instance.employee_ID

        total_income = employee.total_income + (instance.commision_rate / 100) * instance.total_amount

        employee.total_income = total_income

        employee.save()



Register signal handler in your Django apps 'apps.py'

file or any other place where it will be imported and executed during application startup.

# myapp/apps.py


from django.apps import AppConfig


class MyappConfig(AppConfig):

    name = 'myapp'


    def ready(self):

        import myapp.signals  # Import your signals module here

That code signals a certain attribute in one of my application models whenever form is submitted and then continuously does some background task and records in database.From there ave followed normal steps to render my models to django templates.

Some developers tend to avoid django signals and Receivers claiming that it adds some complexity in terms of understanding code.While i agree and disagree it depends who you are and people you are working.



Comments

Popular posts from this blog

Useful learning resources

Remote, hybrid and onsite jobs for software engineers

Tips on accelerating your software engineering career