Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 368
yejinxin Avatar asked Dec 19 '12 10:12

yejinxin


2 Answers

Hm... Is it not working?

class ViewOne(View):
    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):
        ...
    def get(self, request, *args, **kwargs):
        ...    
like image 81
defuz Avatar answered Sep 29 '22 04:09

defuz


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):
    ...
like image 38
surfeurX Avatar answered Sep 29 '22 03:09

surfeurX