request.user in DRF Views vs Django Views

29 views
Skip to first unread message

Praful Bagai

unread,
Jun 4, 2019, 6:00:08 AM6/4/19
to Django REST framework
I'm trying to get the authenticated user in the APIs. Here's the code:-

**DRF View**

    from braces.views import CsrfExemptMixin
    from rest_framework import generics

    class API(CsrfExemptMixin, generics.CreateAPIView):
        authentication_classes = []
        serializer_class = SomeSerializer
    
        def post(self, request):
            print(request.user.id)  # None



**Django View**

    from django.views import View
    from braces.views import CsrfExemptMixin

    class API(CsrfExemptMixin, View):

        def post(self, request):
            print(request.user.id)  # prints id of the user.



Why am I getting different responses in the 2 different scenarios? Following are my settings.


    AUTHENTICATION_BACKENDS = (
        # Needed to login by username in Django admin, regardless of `allauth`
        'django.contrib.auth.backends.ModelBackend',
    
        # `allauth` specific authentication methods, such as login by e-mail
        'allauth.account.auth_backends.AuthenticationBackend',
    
        # Needed to login by email
        'modules.profile.backend.EmailBackend'
    )


    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
        'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
        'EXCEPTION_HANDLER': 'modules.utils.exception_handler.custom_exception_handler',
        'PAGE_SIZE': 10,
    }


My Chrome Extension fires cross-domain request on this POST endpoint. I believe it's right for Views to expect a CSRF token, unless I exempt them explicitly. Hence, I purposely left authentication_classes empty for csrf exempt.

I read somewhere here that with session authentication you need CSRF tokens. Is there a way I can exempt a particular view?

Alan Crosswell

unread,
Jun 4, 2019, 7:39:43 AM6/4/19
to django-res...@googlegroups.com
By setting authentication_classes you are overriding the AUTHENTICATION_BACKENDS?

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/32b95cf9-3e7f-4b70-a60c-41efdf65f0f5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Alan Crosswell
Associate VP & CTO

Reply all
Reply to author
Forward
0 new messages