Stephen Nyamweya
Stephen Nyamweya

Reputation: 114

How do I pass the request object to the method_decorator in django class views?

I have been working on this all day.

I am trying to write custom permission for class views to check if user is in a certain group of permissions.

def rights_needed(reguest):
  if request.user.groups.filter(Q(name='Admin')).exists():
    pass
  else:
    return HttpResponseRedirect('/account/log-in/')

@method_decorator(rights_needed, name='dispatch')
class AdminView(CreateView):
    model = Admin
    form_class = AdminForm
    def get_template_names(self):
        return 'clinic/visitform_list.html'

Could help me know how I can achieve this? Or an easier way around it?

I also tried this (code inside AdminView class):

    def dispatch(self, request):
        if request.user.groups.filter(Q(name='Admin')).exists():
            return super().dispatch(*args, **kwargs)
        else:
            return HttpResponseRedirect('/account/log-in/')

Upvotes: 4

Views: 1776

Answers (1)

Alasdair
Alasdair

Reputation: 308789

A decorator is a function that takes a function (a view in this case), and returns another function (a view in this case). At the moment your rights_needed looks like a regular view - it’s returning a response not a function.

Django comes with a user_passes_test method that makes it easy to create decorators like this. Since you are using class based views, it would be even easier to use the UserPassesTest mixin.

Your test function for the mixin would be:

def test_func(self):
    return self.request.user.groups.filter(Q(name='Admin')).exists()

Upvotes: 2

Related Questions