开发者

Overriding Django views with decorators

I have a situation that requires redirecting users who are already logged in away from the login page to another p开发者_如何转开发age. 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.

Thanks in advance!

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?


Three more ways to do it, though you'll need to use your own urlconf for these:

  1. Add the decorator to the view directly in the urlconf:

    ...
    (regexp, decorator(view)),
    ...
    

    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.

  2. Import the view into an <app>/views.py and add the decorator there:

    import view
    
    view = decorator(view)
    

    Pretty much like Vinay's method though more explicit since you need an urlconf for it.

  3. 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.

Whenever you use an urlconf, order of patterns matter, so you might need to shuffle around on which pattern gets called first.


If you have the decorator function and you know which view in django-registration you want to decorate, you could just do

registration.view_func = decorator_func(registration.view_func)

where registration is the module in django-registration which contains the view function you want to decorate, view_func is the view function you want to decorate, and decorator_func is the decorator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜