You have probably seen some decorators already in Django. I often use decorators for adding authentication to a view, or limiting a view to a specific request method.
Typically when building a SaaS, you use teams. In my case, I want to always have a team activated for the users. But instead of checking this manually in each view, I can just assign a simple decorator:
@active_team_required
def dashboard(request):
...
And the decorator it self is also very simple. It looks like this:
from django.contrib import messages
from django.shortcuts import redirect
def active_team_required(view_func):
def _wrapped_view(request, *args, **kwargs):
if request.user.active_team is None:
messages.error(request, 'No active team')
return redirect('team:index')
return view_func(request, *args, **kwargs)
return _wrapped_view
It even adds a message to the session telling the user what's wrong.