Django Rest Framework和Auth:如何覆盖UserDetailsView

时间:2019-06-24 03:02:30

标签: python django django-rest-framework django-rest-auth

我正在使用django-rest-auth作为自定义用户模型的API端点。获取用户详细信息后,我向GET发送了一个/rest-auth/user/请求。这对于经过身份验证的用户可以正常工作,但是对于带有403 Forbidden错误标记的未经身份验证的用户则禁止这样做。

但是,我希望其他用户能够查看彼此的详细信息。我该如何更改?

此测试是证明此错误的测试:

def test_get_user(self):
        # /rest-auth/user/ (GET)
        # params: username, first_name, last_name
        # returns: pk, username, email, first_name, last_name
        client = APIClient()
        client.login(username=self.user2.username, 
                     password=self.user2.password)

        path = "/rest-auth/user/"
        user_data = {
            "username": self.username,
        }
        expected_response = {
            "pk": self.id,
            "username": self.username,
            "email": self.email,
            "first_name": '',
            "last_name": '',
        }

        response = client.get(path, user_data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, expected_response)

编辑: 我试图覆盖UserDetailsView的权限,但未能正确执行。如何正确执行此操作?

from rest_auth import views
from rest_framework.permissions import IsAuthenticatedOrReadOnly


class CustomUserDetailsView(views.UserDetailsView):
    permission_classes = (IsAuthenticatedOrReadOnly, )

1 个答案:

答案 0 :(得分:1)

django-rest-auth /rest-auth/user/仅允许您获取经过身份验证的用户的详细信息。

class UserDetailsView(RetrieveUpdateAPIView):
"""
Reads and updates UserModel fields
Accepts GET, PUT, PATCH methods.

Default accepted fields: username, first_name, last_name
Default display fields: pk, username, email, first_name, last_name
Read-only fields: pk, email

Returns UserModel fields.
"""
serializer_class = UserDetailsSerializer
permission_classes = (IsAuthenticated,)

def get_object(self):
    return self.request.user

def get_queryset(self):
    """
    Adding this method since it is sometimes called when using
    django-rest-swagger
    https://github.com/Tivix/django-rest-auth/issues/275
    """
    return get_user_model().objects.all()

如果您希望未经身份验证的用户读取所有用户对象,那么您已经编写了自己的视图。

serializers.py

User = get_user_model()
class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = "__all__"

views.py

class UserDetailApiView(generics.RetrieveAPIView):
permission_classes = (IsAuthenticatedOrReadOnly,)
queryset = get_user_model().objects.all()
serializer_class = UserSerializer

urls.py

path('api/users/<int:pk>',views.UserDetailApiView.as_view(),name='user')