django.dispatch Signal Example Code

The Signal class allows certain senders to notify a set of receivers that some action has taken place across Django apps within the same project.

Example 1 from django-simple-history

django-simple-history is a code library that stores Django model state to track history, view and revert changes via the Django admin site. It is open source under the BSD 3-Clause "New" or "Revise" License.

django-simple-history / simple_history / signals.py

# signals.py
import django.dispatch


pre_create_historical_record = django.dispatch.Signal(
    providing_args=[
        "instance",
        "history_instance",
        "history_date",
        "history_user",
        "history_change_reason",
        "using",
    ]
)
post_create_historical_record = django.dispatch.Signal(
    providing_args=[
        "instance",
        "history_instance",
        "history_date",
        "history_user",
        "history_change_reason",
        "using",
    ]
)

Example 2 from aldryn-accounts

aldryn-accounts is a code library for user registration and authentication in Django projects. The code for this project is open source under the MIT license.

aldryn-accounts / aldryn_accounts / signal.py

# -*- coding: utf-8 -*-
import django.dispatch
from django.contrib.auth import user_logged_in
from django.db.models import signals, ObjectDoesNotExist
from django.utils.encoding import force_text
from django.utils import timezone
from django.contrib.auth.models import User

from .utils import generate_username


user_signed_up = django.dispatch.Signal(providing_args=["user", "form"])
user_sign_up_attempt = django.dispatch.Signal(providing_args=["username",  "email", "result"])
signup_code_sent = django.dispatch.Signal(providing_args=["signup_code"])
signup_code_used = django.dispatch.Signal(providing_args=["signup_code_result"])
email_confirmed = django.dispatch.Signal(providing_args=["email_address"])
email_confirmation_sent = django.dispatch.Signal(providing_args=["confirmation"])
password_changed = django.dispatch.Signal(providing_args=["user"])


# code continues from here without any further django.dispatch.Signal references

Example 3 from django-easy-timezones

django-easy-timezones (project website) is a Django middleware code library to simplify handling time data in your applications using users' geolocation data.

django-easy-timezones / easy_timezones / signals.py

# Django
import django.dispatch

detected_timezone = django.dispatch.Signal(providing_args=["instance", "timezone"])

Example 4 from viewflow

viewflow (project website) is a reusable workflow code library for organizing business logic in a complex web application. The code for the project is available under the GNU Alfredo license.

viewflow / viewflow / signals.py

# signals.py
from django.dispatch import Signal

flow_started = Signal(providing_args=["process", "task"])
flow_finished = Signal(providing_args=["process", "task"])

task_started = Signal(providing_args=["process", "task"])
task_failed = Signal(providing_args=["process", "task", "exception", 
                                     "traceback"])
task_finished = Signal(providing_args=["process", "task"])

Example 5 from django-registration (redux)

django-registration (redux) (project documentation) is a Django code library for one-phase, two-phase and three-phase registration flows. The code is available open source.

django-registration / registrations / signals.py

from django.conf import settings
from django.contrib.auth import get_backends
from django.contrib.auth import login
from django.dispatch import Signal

# An admin has approved a user's account
user_approved = Signal(providing_args=["user", "request"])

# A new user has registered.
user_registered = Signal(providing_args=["user", "request"])

# A user has activated his or her account.
user_activated = Signal(providing_args=["user", "request"])


def login_user(sender, user, request, **kwargs):
    """ Automatically authenticate the user when activated  """
    backend = get_backends()[0]  # Hack to bypass `authenticate()`.
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    login(request, user)
    request.session['REGISTRATION_AUTO_LOGIN'] = True
    request.session.modified = True


if getattr(settings, 'REGISTRATION_AUTO_LOGIN', False):
    user_activated.connect(login_user)

Example 6 from django-cors-headers

django-cors-headers is an open source library for enabling Cross-Origin Resource Sharing (CORS) handling in your Django web applications and appropriately dealing with HTTP headers for CORS requests.

django-cors-headers / src / corsheaders / signals.py

from django.dispatch import Signal

# If any attached handler returns Truthy, CORS will be allowed for the request.
# This can be used to build custom logic into the request handling when the
# configuration doesn't work.
check_request_enabled = Signal(providing_args=["request"])

Sponsored By

Sentry logo

Software errors are inevitable. Chaos is not. Try Sentry for free.

1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses Django ExtensionsDjango Example Codedjango.apps.config AppConfigdjango.conf settingsdjango.conf.urls.urldjango.contrib.admindjango.contrib.admin.filters SimpleListFilterdjango.contrib.admin.sites registerdjango.contrib.admin helpersdjango.contrib.admin.helpers ActionFormdjango.contrib.admin.helpers AdminFormdjango.contrib.admin.options IS_POPUP_VARdjango.contrib.admin.options IncorrectLookupParametersdjango.contrib.admin.options ModelAdmindjango.contrib.admin.options csrf_protect_mdjango.contrib.admin.sites NotRegistereddjango.contrib.admin.sites sitedjango.core cachedjango.core checksdjango.core exceptionsdjango.core maildjango.core managementdjango.core serializersdjango.core signalsdjango.core signingdjango.core validatorsdjango.utils translationdjango.utils.translation LANGUAGE_SESSION_KEYdjango.utils.translation activatedjango.utils.translation deactivate_alldjango.utils.translation get_languagedjango.utils.translation get_language_from_requestdjango.utils.translation gettextdjango.utils.translation gettext_lazydjango.utils.translation ngettextdjango.utils.translation overridedjango.utils.translation pgettextdjango.utils.translation pgettext_lazydjango.utils.translation ugettextdjango.utils.translation ugettext_lazydjango.utils.translation ungettextdjango.utils.translation ungettext_lazydjango.utils.version get_complete_versiondjango.views csrfdjango.views.debug get_default_exception_reporter_filterdjango.views.decorators.csrf csrf_exemptdjango.views.decorators.debug sensitive_post_parametersdjango.views.decorators.http require_GETdjango.views.decorators.http require_POSTdjango.views.generic CreateViewdjango.views.generic DeleteViewdjango.views.generic DetailViewdjango.views.generic FormViewdjango.views.generic ListViewdjango.views.generic RedirectViewdjango.views.generic TemplateViewdjango.views.generic UpdateViewdjango.views.generic Viewdjango.views.generic.base RedirectViewdjango.views.generic.base TemplateResponseMixindjango.views.generic.base TemplateViewdjango.views.generic.base Viewdjango.views.generic.detail SingleObjectMixindjango.views.generic.edit CreateViewdjango.views.generic.edit DeleteViewdjango.views.generic.edit DeletionMixindjango.views.generic.edit FormMixindjango.views.generic.edit FormViewdjango.views.generic.list ListViewdjango.views.generic.list MultipleObjectMixindjango.views.i18n JavaScriptCatalogdjango.views.static servedjango.views.static was_modified_sincedjango.contrib.auth.decorators login_requireddjango.contrib.auth get_user_modeldjango.contrib.auth.hashers make_passworddjango.core.exceptions ImproperlyConfigureddjango.core.mail.messages EmailMessagedjango.core.mail.send_maildjango.core.management.base BaseCommanddjango.db.models AutoFielddjango.db.models BooleanFielddjango.db.models CharFielddjango.db.models DateFielddjango.db.models DateTimeFielddjango.db.models FileFielddjango.db.models ForeignKeydjango.db.models GenericIPAddressFielddjango.db.models ImageFielddjango.db.models IntegerFielddjango.db.models Modeldjango.db.models PositiveIntegerFielddjango.db.models PositiveSmallIntegerFielddjango.db.models.signaldjango.db.models SlugFielddjango.db.models SmallIntegerFielddjango.db.models TextFielddjango.db OperationalErrordjango.dispatch Signaldjango.formsdjango.forms BooleanFielddjango.forms CharFielddjango.forms ChoiceFielddjango.forms DateFielddjango.forms DateTimeFielddjango.forms EmailFielddjango.forms IntegerFielddjango.forms TypedChoiceFielddjango.http Http404django.http HttpResponsedjango.http HttpResponseBadRequestdjango.http HttpResponseForbiddendjango.http HttpResponseNotModifieddjango.http HttpResponsePermanentRedirectdjango.http HttpResponseRedirectdjango.template.response SimpleTemplateResponsedjango.template.response TemplateResponsedjango.urls.pathdjango.urls reverse_lazydjango.urls.exceptions NoReverseMatchdjango.urls.exceptions Resolver404django.utils.html format_htmldjango.utils.timezone ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2020