How To Use Login_required In Django Rest View
Solution 1:
I think you are searching for django rest framework APIView; Here you can use permission classes; Refer this documentation http://www.django-rest-framework.org/api-guide/permissions/
Add to seetings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
from rest_framework.permissions import IsAuthenticated
classhome(APIView):
renderer_classes = (TemplateHTMLRenderer,)
permission_classes = (IsAuthenticated,)
defget(self, request, format=None):
template = get_template(template_name='myapp/template.html')
return Response({}, template_name=template.template.name)
Solution 2:
Decorators can only be used on functions, not classes.
However, for decorating class-based views the django docs suggest this:
Decorating the class
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.A method on a class isn’t quite the same as a standalone function, so you can’t just apply a function decorator to the method – you need to transform it into a method decorator first. The
method_decoratordecorator transforms a function decorator into a method decorator so that it can be used on an instance method. For example:from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic import TemplateView classProtectedView(TemplateView): template_name = 'secret.html' @method_decorator(login_required)defdispatch(self, *args, **kwargs): returnsuper(ProtectedView, self).dispatch(*args, **kwargs)
Solution 3:
Since Django 1.9 you can alternatively use a Mixin for controlling permissions in class based views:
https://docs.djangoproject.com/en/1.9/releases/1.9/#permission-mixins-for-class-based-viewshttps://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.mixins.LoginRequiredMixin
Post a Comment for "How To Use Login_required In Django Rest View"