djangodecorator

Django decorators passing variable to views


Hi Iam using Django Decorators.

I want to pass a variable from decorators to views function.

Is it possible means please help me..

def d(msg='my default message', alt="none"):
    def decorator(func):
        def newfn(request, **kwargs):
            if msg and alt:
               variable = "Read Only"
            return func(request, **kwargs)
        return newfn
    return decorator

I want the variable to be passed from decorators to view.

@d('hai', 'begin')
def company(request):
   print variable
   return ...

Anyone help me. Thanks in Advance


Solution

  • You can't manipulate scopes that way.

    def d(msg='my default message', alt="none"):
        def decorator(func):
            def newfn(request, **kwargs):
                if msg and alt:
                   kwargs['variable'] = "Read Only"
                return func(request, **kwargs)
            return newfn
        return decorator
    
    @d('hai', 'begin')
    def company(request, variable):
       print(variable) #available as an argument to this view
       return ...