[Answer]-Is there Django view decorator to check a condition that doesn't assume the input is a User?

1👍

just return a HttpResponseForbidden response object:

from django.http import HttpResponseForbidden

def what_decorator_goes_here(function):
    @wraps(function)
    def check_value(self, *args, **kwargs):
        if getattr(self, 'my_val', None) == 1:
            return function(self, *args, **kwargs)
        else:
            return HttpResponseForbidden()
    return check_value

Or more sophisticated:

def allow_if_view_value(attr_name, target_value):
    def decorator(function):
        @wraps(function)
        def check_value(self, *args, **kwargs):
            if getattr(self, attr_name, None) == target_value:
                return function(self, *args, **kwargs)
            else:
                return HttpResponseForbidden()
        return check_value
    return decorator

@allow_if_view_value('my_val', 1)
[...]

Albeit I must say, I am not too fond of using decorators to accomplish this instead of a generic view base class that dispatches requests accordingly.

👤dhke

0👍

I think you should just be able to raise a PermissionDenied Exception from the decorator itself.

from django.core.exceptions import PermissionDenied

def my_decorator_1(function):
    @wraps(function)
    def decorator(self, *args, **kwargs):
        self.my_val = random.randint(0,1)
        if self.my_val == 1:
            raise PermissionDenied
        return function(self, *args, **kwargs)
    return decorator

I think thats how the decorators you’ve mentioned work. The Django request pipeline would then pick up the exception and handle it accordingly.

Leave a comment