20.4.1 Custom Decorators

Having to override dispatch() in each and every one of our views is an unacceptable method for adding permissions. We should be able to use decorators on our class-based views directly. Even though Django doesn’t supply this behavior, because this is all Python, we can create our own decorators.

Decorators are one of Python’s trickier techniques, and even though Appendix B provides a primer on the material, we will take this slowly. To begin, we recreate the @login_required decorator a new file called user/decorators.py, as shown in Example 20.39.

Example 20.39: Project Code

user/decorators.py in 47885ef1d7

 1   from django.conf import settings  2   from django.contrib.auth import get_user ...

Get Django Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.