用装饰器覆盖Django视图 [英] Overriding Django views with decorators
问题描述
我有一种情况,需要将已经登录的用户从登录页面重定向到另一个页面。我已经看到提到这可以通过装饰器来实现,但是我使用它是相当新的。但是,我使用django登录和第三方视图(从django注册)。我不想更改django.contrib.auth或django注册中的任何代码。为了获得所需的行为,我如何将装饰器应用于不被修改的视图。
I have a situation that requires redirecting users who are already logged in away from the login page to another page. I have seen mention that this can be accomplished with decorators which makes sense, but I am fairly new to using them. However, I am using the django login and a third party view (from django-registration). I do not want to change any of the code in django.contrib.auth or django-registration. How can I apply a decorator to a view that is not to be modified in order to get the desired behavior.
提前感谢!
更新:我发现我错误地将登录功能与注册模块相关联。 django注册与这个问题无关。但是,我仍然需要覆盖默认的login()行为。任何想法?
UPDATE: I discovered that I mistakenly associated the login function with the registration module. django-registration has nothing to do with this issue. However, I still need to be able to override default login() behavior. Any thoughts?
推荐答案
有三种方法可以实现,虽然您需要使用自己的urlconf来实现这些功能: p>
Three more ways to do it, though you'll need to use your own urlconf for these:
-
直接在urlconf中将修饰器添加到视图中:
Add the decorator to the view directly in the urlconf:
...
(regexp, decorator(view)),
...
你需要将视图和装饰器导入urlconf,这就是为什么我不喜欢这个。我更喜欢在我的urls.py中输入尽可能少的导入。
You need to import the view and the decorator into the urlconf though, which is why I don't like this one. I prefer to have as few imports in my urls.py's as possible.
将视图导入< app> / views .py
并在其中添加装饰器:
Import the view into an <app>/views.py
and add the decorator there:
import view
view = decorator(view)
非常像Vinay的方法,因为你需要一个urlconf更加明确。
Pretty much like Vinay's method though more explicit since you need an urlconf for it.
将视图包裹在新视图中:
Wrap the view in a new view:
import view
@decorator
def wrapperview(request, *args, **kwargs):
... other stuff ...
return view(request, *args, **kwargs)
最后一个在您需要更改通用视图时非常方便。这是我经常最终做的。
The last one is very handy when you need to change generic views. This is what I often end up doing anyway.
每当你使用urlconf,模式的顺序都很重要,所以你可能需要首先调用哪个模式被调用。
Whenever you use an urlconf, order of patterns matter, so you might need to shuffle around on which pattern gets called first.
这篇关于用装饰器覆盖Django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!