2

I have view:

@decorator
def func(request):
  hello = "hello"
  return render_to_responce("test.html", locals() )

and template test.html:

{{ hello }}
{{ username }}

I want to write decorator for func(request), which adds a variable, USERNAME, to the function and returns two parameters in the template. I tried to make it as follows:

def decorator(func):
    def wrapper( request, *args, **kwargs):
        username = request.user.username
        q = func(request, *args, **kwargs)
        #what I need add here I do not know ...
        return q   
    return wrapper
Ben
  • 51,770
  • 36
  • 127
  • 149
kusha
  • 151
  • 1
  • 4
  • 6
  • Why do you think you want a decorator? Could you explain the use-case? (could you also clean up your code so that it's syntactically correct and more readable)? – Jon Clements Aug 05 '12 at 16:00

1 Answers1

7

If your view looks like this:

def func(request, username):
    hello = "hello"
    return render_to_responce("test.html", locals() )

you can write a decorator like that:

from functools import wraps
def pass_username(view):
    @wraps(view)
    def wrapper(request, *args, **kwargs):
        return view(request, request.user.username, *args, **kwargs)
    return wrapper

and then use it like that:

@pass_username
def func(request, username):
    hello = "hello"
    return render_to_response("test.html", locals())

(just make sure you will treat it in urls.py as if it was def func(request):, without username - this argument will be provided by the decorator)

But indeed this is very simple case that does not really require separate decorator (anyway, it is only one additional line in the view definition).

Tadeck
  • 132,510
  • 28
  • 152
  • 198