[英]Django Custom View Decorators
Alright I have a method called no_m in the user class and i've not written a decorator before, but basically I need to redirect the user to another URL if they pass this. 好吧我在用户类中有一个名为no_m的方法,我之前没有写过装饰器,但基本上我需要将用户重定向到另一个URL,如果他们通过了这个。 I have created a file called decorators.py in a dir called accounts and i'm guessing the decorator is imported correctly, however I cannot get it to work.
我在一个名为accounts的目录中创建了一个名为decorators.py的文件,我猜测装饰器是否正确导入,但我无法让它工作。 Heres what I have:
继承人我所拥有的:
def no_m(view_func):
def _wrapped_view_func(request, *args, **kwargs):
try:
if request.user.is_m():
# quick test
return HttpResponseRedirect('http://google.com')
else:
return view_func(request, *args, **kwargs)
except:
return _wrapped_view_func
All it needs to do is redirect users if they pass that test, I don't know what the URL needs to be yet so it's just google for now. 所有它需要做的是重定向用户,如果他们通过该测试,我不知道URL需要什么,所以它只是谷歌现在。 Any ideas?
有任何想法吗? Like I said, i've not written decorators before so it's all new to me.
就像我说的那样,我之前没有写过装饰器,所以这对我来说都是新的。 Thankyou.
谢谢。
Another thought: would it be possible to render a template page? 另一个想法:是否可以渲染模板页面?
You're missing a step in the decorator, or rather you have a step confused. 你错过了装饰者的一个步骤,或者说你有一个困惑的步骤。 It's the outer function that must return the inner function (
_wrapped_view_func
), and it must always do so: that's what takes the place of the original function when it is called. 它是必须返回内部函数(
_wrapped_view_func
)的外部函数,它必须始终这样做:这就是在调用它时取代原始函数的原因。
I'm not sure what the except clause is there for. 我不确定except子句是什么的。 Apart from it always being a bad idea to use a blank except - that catches everything , including things like ctrl-c - exceptions in Django functions are usually handled by the middleware, rather than the decorator.
除了捕获所有内容 (包括ctrl-c之类的东西)之外总是使用空白总是一个坏主意 - Django函数中的异常通常由中间件而不是装饰器处理。 I would just remove it.
我会删除它。
So the code should be: 所以代码应该是:
def no_m(view_func):
def _wrapped_view_func(request, *args, **kwargs):
if request.user.is_m():
# quick test
return HttpResponseRedirect('http://google.com')
else:
return view_func(request, *args, **kwargs)
return _wrapped_view_func
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.