Overriding Django views with decorators

喜夏-厌秋 提交于 2019-12-21 22:46:04

问题


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.

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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1649351/overriding-django-views-with-decorators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!