Search code examples
pythondjangopython-2.7decoratorpython-decorators

Making decorator for class method in Django


I'm founded staff_member_required for function-based views, but didn't find for class methods. Well, I'm tried to write decorator for my class-based view:

from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic import View

def cls_method_staff_member_decorator(func):
    def wrapper(self, request, *args, **kwargs):
        return staff_member_required(view_func=func)(request, *args, **kwargs)
    return wrapper

class SetUserData(View):
    http_method_names = ['get', ]

    @cls_method_staff_member_decorator
    def get(self, request, user_id):
        # ... some actions with data

But after starting server via runserver command, taking error:

TypeError at /en-us/user/userdata/7/ get() takes exactly 3 arguments (2 given)

How can I fix it?


Solution

  • You need to decorate the dispatch method by using the method_decorator.

    class SetUserData(View):
        @method_decorator(cls_method_staff_member_decorator)
        def dispatch(self, *args, **kwargs):
            return super(SetUserData, self).dispatch(*args, **kwargs)
    

    Explained here

    Alternatively decorate in urls:

    urlpatterns = patterns('',
        ...
        (r'^your_url/', cls_method_staff_member_decorator(SetUserData.as_view())),
        ...
    )