Overriding Django views with decorators

点点圈 提交于 2019-12-04 19:46:45

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.

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