djugl 2015 signals and appconfig

27
SIGNALS AND APPCONFIG DJUGL October 6, 2015

Upload: ana-balica

Post on 15-Apr-2017

493 views

Category:

Technology


2 download

TRANSCRIPT

SIGNALS AND

APPCONFIG

DJUGL October 6, 2015

@anabalica

Let’s get schwifty with !

from django.db.models.signals import post_savefrom django.dispatch import receiverfrom myapp.models import MyModel

@receiver(post_save, sender=MyModel)def my_handler(sender, **kwargs): pass

# my_app/signals.py

from django.db.models.signals import pre_savefrom django.dispatch import receiverfrom myapp.models import MyModel

@receiver(pre_save, sender=MyModel)def my_handler(sender, **kwargs): pass

# my_app/signals.py

Django<1.7?

make sure that the module it’s in gets imported early on so that the signal handling gets registered before any signals need to be sent

Django<1.7?

make sure that the module it’s in gets imported early on so that the signal handling gets registered before any signals need to be sent

Django<1.7?

this makes your app’s models.py a good place to put registration of signal handlers

from django.db import modelsfrom my_app import signals

class MyModel(models.Model): pass

# my_app/models.py

CIRCULAR IMPORTS

from my_app import signals

# my_app/__init__.py

AppConfig to the rescue

AppConfig is a registry of installed apps and available

models

>>> from django.apps import apps>>> apps.get_app_config('admin').verbose_name'Admin'

from django.apps import AppConfig

class RickNMortyConfig(AppConfig): name = "rick_n_morty" verbose_name = "Rick and Morty"

# my_app/apps.py

INSTALLED_APPS = [ "my_app.apps.RickNMortyConfig", # ...]

# settings.py

or

default_app_config = "my_app.apps.RickNMortyConfig"

# my_app/__init__.py

from django.apps import AppConfig

class RickNMortyConfig(AppConfig): name = "rick_n_morty" verbose_name = "Rick and Morty”

def ready(self): from my_app import signals

# my_app/apps.py

•Loads the settings

•Loads the settings•Sets up logging

•Loads the settings•Sets up logging•Initializes the application registry

• Imports each item from INSTALLED_APPS

• Imports each item from INSTALLED_APPS

• Imports the models submodule if exists

• Imports each item from INSTALLED_APPS

• Imports the models submodule if exists

• Runs the ready() method of each app config