Upgrade to Pro — share decks privately, control downloads, hide ads and more …

[DJUGL] Signals and AppConfig

2a3082799c3df9a58d06bc1b81107752?s=47 Ana Balica
October 06, 2015

[DJUGL] Signals and AppConfig

Django User Group in London meetup and my talk about "Signals and AppConfig" Rick and Morty style!

2a3082799c3df9a58d06bc1b81107752?s=128

Ana Balica

October 06, 2015
Tweet

Transcript

  1. SIGNALS AND APPCONFIG DJUGL October 6, 2015

  2. @anabalica

  3. Let’s get schwifty with !

  4. from django.db.models.signals import post_save from django.dispatch import receiver from myapp.models

    import MyModel @receiver(post_save, sender=MyModel) def my_handler(sender, **kwargs): pass # my_app/signals.py
  5. from django.db.models.signals import pre_save from django.dispatch import receiver from myapp.models

    import MyModel @receiver(pre_save, sender=MyModel) def my_handler(sender, **kwargs): pass # my_app/signals.py
  6. 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
  7. 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
  8. Django<1.7? this makes your app’s models.py a good place to

    put registration of signal handlers
  9. from django.db import models from my_app import signals class MyModel(models.Model):

    pass # my_app/models.py
  10. None
  11. CIRCULAR IMPORTS

  12. from my_app import signals # my_app/__init__.py

  13. None
  14. AppConfig to the rescue

  15. AppConfig is a registry of installed apps and available models

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

  17. from django.apps import AppConfig class RickNMortyConfig(AppConfig): name = "rick_n_morty" verbose_name

    = "Rick and Morty" # my_app/apps.py
  18. INSTALLED_APPS = [ "my_app.apps.RickNMortyConfig", # ... ] # settings.py or

    default_app_config = "my_app.apps.RickNMortyConfig" # my_app/__init__.py
  19. None
  20. 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
  21. • Loads the settings • Sets up logging • Initializes

    the application registry
  22. • Imports each item from INSTALLED_APPS • Imports the models

    submodule if exists • Runs the ready() method of each app config
  23. None