On 19 October 2010 19:06, Valentin Golev <[email protected]> wrote:
> Hello,
>
> I'm trying to start using new class based views from the trunk.
>
> I need to rewrite a view which is decorated
> django.contrib.auth.decorators.login_required.
>
> How should I go with that?
There are couple of options.

1) decorate the final view (for use in urls.py):

   decorated_view = login_required(MyView.as_view)

In this option, you lose the ability to subclass the decorated view.

2) decorate the dispatch method. You need to turn login_required into
a method decorator first (Django should probably provide a tool for
this). Here[1] is an example how to do this.

class MyDecoratedView(MyView):

    @on_method(login_required):
    def dispatch(self, *args, **kwargs):
        # do any extra stuff here
        return super(MyDecoratedView, self).dispatch(*args, **kwargs)

3) Make a class decorator, that does the above, so you could do:

@on_dispatch(login_required)
class MyDecoratedView(MyView):
    pass

>
> I was going to write something like LoginRequiredMixin, but I have no
> idea how to do this. I need to run my code before .dispatch(), but I
> also have to call the old dispatch, but since Mixin aren't inherited
> from View, I can't just override method and use super().

This is option #4. You can just do:

class LoginRequiredMixin(object):

    def dispatch(self, *args, **kwargs):
        bound_dispatch = super(LoginRequired, self).dispatch
        return login_required(bound_dispatch)(*args, **kwargs)


[1]: http://www.toddreed.name/content/django-view-class/

-- 
Łukasz Rekucki

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to