Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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/')
like image 628
Stephen Nyamweya Avatar asked Oct 14 '25 12:10

Stephen Nyamweya


1 Answers

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()
like image 176
Alasdair Avatar answered Oct 17 '25 00:10

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!