You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中request.user在视图不同方法中表现异常的问题求助

Django APIView: test_func Sees Authenticated User but get() Returns AnonymousUser

Let me break down why this is happening and how to fix it properly.

What's Causing the Issue?

You’re mixing Django’s native view mixins (LoginRequiredMixin, UserPassesTestMixin) with Django REST Framework (DRF) GenericAPIView, which creates a mismatch in how the request is processed:

  1. Mixin Execution Order: Django runs mixins left to right. Your LoginRequiredMixin and UserPassesTestMixin execute before DRF’s GenericAPIView handles the request.
  2. Request Object Difference:
    • In test_func(), self.request is still Django’s native HttpRequest object, which already passed Django’s session authentication (thanks to LoginRequiredMixin), so it shows the authenticated user.
    • Once DRF’s GenericAPIView takes over, it wraps the native request into a DRF-specific Request object. If DRF isn’t configured to recognize Django’s session authentication, this wrapped request defaults to AnonymousUser.

DRF has its own permission framework designed for APIs, so it’s better to replace Django’s mixins entirely. Here’s how:

First, create a custom permission class for the "Poster" group check:

from rest_framework.permissions import BasePermission, IsAuthenticated

class IsPoster(BasePermission):
    def has_permission(self, request, view):
        # Verify user is authenticated AND part of the Poster group
        return request.user.groups.filter(name='Poster').exists()

Then update your view to use DRF permissions:

class IndexView(generics.GenericAPIView):
    serializer_class = IndexSerializer
    permission_classes = [IsAuthenticated, IsPoster]  # DRF-native permissions

    def get(self, request, *args, **kwargs):
        print(request.user)  # Now shows the authenticated User object
        return HttpResponse('Welcome')

Fix 2: Fix Authentication Configuration (If You Insist on Django Mixins)

If you want to keep using Django’s mixins, ensure DRF recognizes Django’s session authentication by adding this to your settings.py:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        # Add other auth classes like TokenAuthentication if needed
    ]
}

This tells DRF to use Django’s session auth to populate the user in its wrapped request. Note this is less idiomatic for DRF APIs, so stick to Fix 1 whenever possible.

Key Takeaway

Django’s native mixins work for server-rendered views, but DRF’s own authentication/permission tools integrate seamlessly with API request handling. Using DRF’s system avoids confusing request object mismatches like this one.

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:54:06