Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class-based views: where to check for permissions?

Tags:

python

django

I am not very comfortable using class-based views but I am aware of their perks so I am forcing myself to start using them more often.

There's this view that receives a path param: manage/:id to manage a particular entity.

class MyView(TemplateView):
  template_name = '...'

  def get_context_data(self, **kwargs):
    context = super(MyView, self).get_context_data(**kwargs)
    context['entity'] = get_object_or_404(Entity, pk=self.args[0])
    return context

An Entity includes a list of authorized users to perform special actions. This view, MyView is one of those special actions.

I tried making a decorator for the view but it required finding the Entity first so I wasn't sure how to work that out.

Now, I have a check_permission(request, entity) function that checks if the current user is one of these authorized ones.

My question is where should I call this function in the class-based views like MyView which will be any of these views considered "special actions"?

Should I call it just from get_context_data()?

like image 744
dabadaba Avatar asked Jan 18 '17 17:01

dabadaba


1 Answers

put it into dispatch(). It could look like this:

class MyView(TemplateView):
   template_name = '...'

   def dispatch(self, request, *args, **kwargs):
       entity = get_object_or_404(Entity, pk=args[0])
       if not check_permission(request, entity):
           raise Http404
       return super(MyView, self).dispatch(request, *args, **kwargs)
like image 161
yedpodtrzitko Avatar answered Nov 07 '22 02:11

yedpodtrzitko