如何在Django中创建装饰器来装饰视图 [英] How create decorator in Django for decorating view
问题描述
我有看法:
@decorator
def func(request):
hello = "hello"
return render_to_responce("test.html", locals() )
和模板test.html:
and template test.html:
{{ hello }}
{{ username }}
我想为 func(request)
编写装饰器,它添加了一个变量, 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
推荐答案
如果您的看法如下所示:
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
然后使用它:
@pass_username
def func(request, username):
hello = "hello"
return render_to_response("test.html", locals())
(只是确保你会在 urls.py
中处理它,就好像它是 def func请求):
,没有用户名
- 此参数将由装饰器提供)
(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).
这篇关于如何在Django中创建装饰器来装饰视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!