Django View Decorator

Today for a contract, I worked on a redirect that checked to see if user had a profile or was authenticated. Simple enough, but you may not know how to do it in Django!

Here’s how:

def profile_required():
    def decorator(view):
        @wraps(view)
        def _wrapped_view(request, *args, **kwargs):
            if not request.user.is_authenticated:
                return HttpResponseRedirect(reverse("login"))
            
            if not request.user.profile or not request.user.profile.organization:
                return HttpResponseRedirect(reverse("no-organization"))
            
            return view(request, *args, **kwargs)
        return _wrapped_view
    return decorator

All via a standard decorator! Then within that wrapped view function, I can do things like check my request for the profile and associated organization.

@profile_required()
def home(request):
    """
    View that renders the home page with Material Design layout.
    If the user's profile is empty, display a form to complete it.
    """
    # ...

Then you can wrap your views just like other decorators, and use that to handle the custom checking. Works like a charm

 Share!

 
I run WindleWare! Feel free to reach out!

Subscribe for Exclusive Updates

* indicates required