Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2 

3Abstract 

4-------- 

5 

6Inspired by Wagtail's hooks, SuperDjango's hooks system is simple, yet powerful alternative to Django's signals and 

7receivers. 

8 

9Install 

10------- 

11 

12No additional installation steps are required to use hooks. 

13 

14Usage 

15----- 

16 

17Defining a Hook 

18............... 

19 

20Hooks may be defined anywhere in code that is loaded and executed as part of Django operation. For example, the 

21:py:class:`superdjango.contrib.accounts.auth.views.LoginRedirect` view defines a hook that may be used to override the 

22post-login redirect URL: 

23 

24.. code-block:: python 

25 

26 from superdjango.interfaces.hooks import hooks 

27 

28 class LoginRedirect(RedirectView): 

29 # ... 

30 

31 def get_redirect_url(self, *args, **kwargs): 

32 results = hooks.get_hooks("get_login_redirect_url") 

33 if results: 

34 return results[0](self.request) 

35 

36 # ... 

37 

38Documenting a Hook 

39.................. 

40 

41To help others understand how a hook works, you may define the hook in the ``meta.ini`` file of the app or package. For 

42example: 

43 

44.. code-block:: ini 

45 

46 [hooks] 

47 get_login_redirect_url = (request): Return a URL string to override the post-login redirect behavior. 

48 

49Auto-documentation scripts may now provide a list of provided hooks dynamically. 

50 

51Responding to a Hook 

52.................... 

53 

54Responding to a hook requires 1) defining a function, 2) registering the function, and 3) making sure the code is loaded. 

55For example: 

56 

57.. code-block:: python 

58 

59 # myapp/hooks.py 

60 from superdjango.interfaces.hooks import hooks 

61 

62 def get_login_redirect_url(request): 

63 if request.user.is_superuser: 

64 return "/admin/" 

65 else: 

66 return "/" 

67 

68 hooks.register(get_login_redirect_url, hook="get_login_redirect_url") 

69 

70The hook name, if omitted defaults to the name of the provided function. So the register statement could simply be 

71written as: 

72 

73.. code-block:: python 

74 

75 hooks.register(get_login_redirect_url) 

76 

77Finally, you can use the ``ready()`` method to load the hooks: 

78 

79.. code-block:: python 

80 

81 # myapp/apps.py 

82 from django.apps import AppConfig 

83 

84 class DefaultConfig(AppConfig): 

85 name = 'myapp' 

86 

87 def ready(self): 

88 from . import hooks 

89 

90""" 

91__author__ = "Shawn Davis <shawn@superdjango.com>" 

92__maintainer__ = "Shawn Davis <shawn@superdjango.com>" 

93__version__ = "0.4.0-x" 

94 

95from .library import HookManager 

96 

97hooks = HookManager()