I am developing a site with django 1.8. This is an example of one of the Views:
class ProfileView(View):
template_name = 'index.html'
# Return profile of any role (client/employee/admin)
# Login required
def get(self, request, *args, **kwargs):
try:
profile = Profile.objects.get(user=request.user)
agency = None
if request.user.is_employee():
employee = EmployeeProfile.objects.get(profile=profile)
agency = employee.agency
if request.user.is_manager():
agency = Agency.objects.get(manager=request.user)
except (Profile.DoesNotExist, EmployeeProfile.DoesNotExist, Agency.DoesNotExist) as e:
return HttpResponseRedirect('/404')
return render(request, self.template_name, {"profile": profile, "agency": agency})
# Client sign up
# No decorator is needed
def post(self, request):
sign_up = SignUpForm(request.POST, request.FILES)
response = json.loads(utils.create_user(sign_up,request.POST['avatar']))
if response['profile'] is None:
return JsonResponse({"code": 400, "response": response['message']})
profile = serializers.deserialize("json", response['profile']).next().object
group = Group.objects.get(name='clients')
profile.user.groups.add(group)
return HttpResponseRedirect('/')
The question is, can I have different decorators according to the type of request that is made to a controller (view)?
You need to apply the decorator to the dispatch method of the class based view. This can be done as follows: class ProfileView(View): @youdecorator def dispatch(self,request,*args,**kwargs): return super(ProfileView,self). dispatch(request,*args,**kwargs) //Rest of your code.
To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class. The decorators will process a request in the order they are passed to the decorator.
In Python, the @classmethod decorator is used to declare a method in the class as a class method that can be called using ClassName. MethodName() . The class method can also be called using an object of the class. The @classmethod is an alternative of the classmethod() function.
Since Django 1.9, as per the docs, it is possible to apply decorator in the next way:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
@method_decorator(login_required, name='dispatch')
class YourClassBasedView(TemplateView):
...
where name
is the name of the method to be decorated.
or in case of few decorators:
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.utils.decorators import method_decorator
decorators = [never_cache, login_required]
@method_decorator(decorators, name='dispatch')
class YourClassBasedView(TemplateView):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With