Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 450
Raji Avatar asked Oct 24 '25 20:10

Raji


1 Answers

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 ...
like image 87
Ignacio Vazquez-Abrams Avatar answered Oct 26 '25 14:10

Ignacio Vazquez-Abrams