python - Django Rest 框架和身份验证 : How to override UserDetailsView

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

我正在使用 django-rest-auth 作为我的自定义用户模型的 API 端点。获取用户详细信息,我向 /rest-auth/user/ 发送 GET 请求。这对于经过身份验证的用户来说效果很好,但对于标记有 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, )

最佳答案

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()

如果您希望未经身份验证的用户读取您自己编写的 View 的所有用户对象。

序列化器.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')

关于python - Django Rest 框架和身份验证 : How to override UserDetailsView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729383/

相关文章:

python - 通过 groupby 函数选择组

python - PIL draw.text() 将包含阿拉伯连字的字符串显示为两个单独的字形

python - 如何在 pytest 中为模拟函数提供不同的返回值?

python - 在类中加载外部模块时无法加载 apache 服务器

django - 在 Django 中,我将如何发送 http ://localhost:8000/to a dynamic location 的请求

Django Rest Framework 不创建表 authtoken_token

django-rest-framework 身份验证 : require key parameter in URL?

python - 使用 s3fs(由 dask)测试模拟 S3 存储桶的行为是意外的

javascript - 如何将 Python 列表传递给 HTML 级别的 Javascript

python - 检查ManyToMany字段中的对象是否为Django Rest框架