Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django permission_required decorator method_decorator in CreateView for get_success_url(self)

    from django.contrib.auth.decorators import permission_required  
    from django.utils.decorators import method_decorator  
    class EnvCreate(CreateView):

           model = Capacity.models.Env
           fields = ["name","dns","manager"]
           template_name_suffix = '_create_form'

           @method_decorator(permission_required('Capacity.add_env'))
           def get_success_url(self):
                  return reverse("envapps", kwargs={"envid": self.object.pk})

I want to allow a user to be able to add a 'env' only if he has permission.
I have read many messages and blogs and the method to do the same is as above.
But everywhere dispatch() is being used, but i wanted to use it before get_success_url (not sure if this is the problem)

The error i get when i try to create env (by a user who has permission) i get,

    TypeError at /Capacity/create/
    _wrapped_view() takes at least 1 argument (0 given)
    Request Method: POST
    Request URL:    http://172.16.68.20:7000/Capacity/create/
    Django Version: 1.6.1
    Exception Type: TypeError
    Exception Value: _wrapped_view() takes at least 1 argument (0 given)
    Exception Location: /usr/lib/python2.6/site-packages/django/utils/decorators.py in _wrapper, line 29

Any idea about what am i doing wrong or what can be the solution?

like image 717
Ashwin Sethi Avatar asked Mar 20 '23 21:03

Ashwin Sethi


1 Answers

Got the answer. Was making a mistake in understanding the use of dispatch.

    from django.contrib.auth.decorators import permission_required
    from django.utils.decorators import method_decorator
    class EnvCreate(CreateView):

       model = Capacity.models.Env
       fields = ['name','dns','manager']
       template_name_suffix = '_create_form'

       @method_decorator(permission_required('Capacity.add_env',raise_exception=True))
       def dispatch(self, request):
            return super(EnvCreate, self).dispatch(request)

       def get_success_url(self):
            return reverse('envapps', kwargs={'envid': self.object.pk})
like image 79
Ashwin Sethi Avatar answered Apr 06 '23 03:04

Ashwin Sethi