Opened 9 years ago

Closed 9 years ago

#25798 closed Bug (invalid)

RedirectView providing different request object to decorator

Reported by: connexion2000 Owned by: nobody
Component: Uncategorized Version: 1.9rc1
Severity: Normal Keywords: decorator
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have my own simple decorator:

def ensure_user_has_profile(view_func):
    def _decorator(request, *args, **kwargs):
        if request.user:
            if request.user.is_authenticated():
                if not hasattr(request.user, 'profile'):
                    profile = Profile()
                    profile.user = request.user
                    profile.save()

        response = view_func(request, *args, **kwargs)
        return response

    return wraps(view_func)(_decorator)

However when RedirectView is decorated with above decorator it causes an error:

'HomeView' object has no attribute 'user'

to make it work I need to access user by typing: request.request.user. Then it works with RedirectView, but not with other views.

Change History (1)

comment:1 by Marten Kenbeek, 9 years ago

Resolution: invalid
Status: newclosed

What you pass as request is actually the view instance. You cannot decorate a class method directly if your _decorator() function does not accept self as its first argument. Instead, you need to use method_decorator or decorate the view function returned by View.as_view().

This is also explained in the documentation on decorating class-based views.

Note: See TracTickets for help on using tickets.
Back to Top