Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use login_required in django rest view

I am trying to use a custom login url in specific view

@login_required(login_url='/account/login/')
class home(APIView):
    renderer_classes = (TemplateHTMLRenderer,)

    def get(self, request, format=None):
        template = get_template(template_name='myapp/template.html')
        return Response({}, template_name=template.template.name)

but the traceback shows

File "django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "django/contrib/auth/decorators.py", line 22, in _wrapped_view
    return view_func(request, *args, **kwargs)
TypeError: __init__() takes exactly 1 argument (2 given)

Is it possible to use custom login_required in class-based view?

thank you!

like image 600
alec.tu Avatar asked Oct 20 '15 08:10

alec.tu


People also ask

Can we use Django for REST API?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.

What does @login_required do in Django?

Django's login_required function is used to secure views in your web applications by forcing the client to authenticate with a valid logged-in User.

What is renderers in Django REST Framework?

Renderers are used to serialize the response into a specific media type like JSON, XML, YAML, etc. Django REST Framework provides various built-in renderer classes and it also supports to write a custom renderer. We specify renderers as an iterable type (i.e tuple, list, set, etc.).


1 Answers

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

class home(APIView):
   renderer_classes = (TemplateHTMLRenderer,)
   permission_classes = (IsAuthenticated,)

   def get(self, request, format=None):
       template = get_template(template_name='myapp/template.html')
       return Response({}, template_name=template.template.name)
like image 80
Geo Jacob Avatar answered Oct 05 '22 23:10

Geo Jacob