yejinxin
yejinxin

Reputation: 596

How to decorate different http method in a single class based view

For example, I have a class based view which allows both GET and POST method, as below,

class ViewOne(View):
    def post(self, request, *args, **kwargs):
        ...
    def get(self, request, *args, **kwargs):
        ...
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ViewOne, self).dispatch(*args, **kwargs)

Now, both GET and POST are login_required. But what if I want only POST to be login_required?

Upvotes: 7

Views: 313

Answers (2)

surfeurX
surfeurX

Reputation: 1252

Why don't create two classes, use also django-braces ;)

class ViewOne(View):
    def get(self, request, *args, **kwargs):
    ...

class ViewTwo(LoginRequiredMixin, ViewOne):
    def post(self, request, *args, **kwargs):
    ...

Upvotes: 1

defuz
defuz

Reputation: 27611

Hm... Is it not working?

class ViewOne(View):
    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):
        ...
    def get(self, request, *args, **kwargs):
        ...    

Upvotes: 4

Related Questions