Django REST Framework 仅允许 super 用户访问 api Web View

标签 django django-rest-framework django-authentication

我正在使用 Django 2.0Django RESET Framework 为我的应用程序编写 REST API

我配置了以下身份验证方法

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
}

到目前为止,它允许所有经过身份验证的用户访问 web api View 。

我想要的是允许少数用户(可能是 super 管理员用户)能够通过 session 身份验证或通过登录从网络浏览器访问 API。

Edit 2: contacts/views.py

class ContactViewSet(viewsets.ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated,)

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user)

最佳答案

对于Django 2(在views.py中添加)

from rest_framework.permissions import IsAdminUser

class IsSuperUser(IsAdminUser):
    def has_permission(self, request, view):
        return bool(request.user and request.user.is_superuser)

class ListSmth(ListCreateAPIView):
    permission_classes = (IsSuperUser,)
    ... Your code...

关于Django REST Framework 仅允许 super 用户访问 api Web View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50333330/

相关文章:

python - 在 session 中保留 Django 用户

python - 如何根据其他字段值的条件逻辑设置模型 bool 字段

python - 如何在django中连接mysql

Django 更改继承的表单元类

django - mod_wsgi 和多个项目

python - Django FilterSet AND(?)条件

django-rest-framework - 在序列化程序中添加深度属性后,外键字段在 swagger 文档中消失

python - 在 django REST 框架中序列化一对多关系

django - 控制 Django auth 用户对特定对象实例的访问

python - Django 自定义身份验证后端似乎没有被调用?