Make your own decorators using Django

Make your own decorators using Django

/ #Django


By using a decorator, you can save your self both time and prevent repeating your code.

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.

Comments

No comments yet...

Add comment

Please log in to comment.

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.