【问题标题】:You do not have permission to perform this action when accessing api in django在 django 中访问 api 时您无权执行此操作
【发布时间】:2018-12-28 10:09:57
【问题描述】:

我正在尝试使用 Django rest 框架在我的 Django 应用程序中添加自定义权限。我创建了一个 API,并在邮递员中对其进行了测试,它对于经过身份验证的用户来说效果很好。但是,当我访问详细信息视图时,它不显示详细信息。例如,当我访问http://localhost:8000/placeslist/ 时,它会显示所有地点,但是当我尝试http://localhost:8000/placeslist/1/ 时,它说您没有权限。我不知道我哪里出错了

models.py

class Places(BaseModel):
  name = models.CharField(max_length=255,null=True,default='')
  owner=models.ForeignKey('auth.User',related_name='place_list',on_delete=models.CASCADE,null=True)    

Views.py

class PlacesView(generics.ListCreateAPIView):
    queryset = Places.objects.all()
    serializer_class = PlacesSerializer
    permission_classes = (permissions.IsAuthenticated, IsOwner)

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


class PlacesDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Places.objects.all()
    serializer_class = PlacesSerializer
    permission_classes = (permissions.IsAuthenticated, IsOwner)

Permission.py

class IsOwner(BasePermission):
  def has_object_permission(self, request, view, obj):
    if isinstance(obj, Places):
        return obj.owner == request.user       
    return obj.owner == request.user    

Serializer.py

class PlacesSerializer(serializers.ModelSerializer):
  owner = serializers.ReadOnlyField(source='owner.username')
  class Meta:
    model = Places
    fields =('id','name','owner')

urls.py

url(r'^placeslist/$', PlacesView.as_view(), name="place"),
url(r'placeslist/(?P<pk>[0-9]+)/$',PlacesDetailView.as_view(), 
name="place_details"),
url(r'^get-token/', obtain_auth_token),

Settings.py

....

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.TokenAuthentication',
)
}

....

【问题讨论】:

    标签: django django-rest-framework django-permissions


    【解决方案1】:

    这是因为您的自定义权限在您尝试访问所有者不是您当前使用的用户的实例(pk = 1 的地方)。

    检查那个地方的所有者。

    您可以删除视图上的permissions.IsAuthenticated,因为您已经将它放在了默认权限类中。

    【讨论】:

    • 确保您的设置 DEFAULT_PERMISSION_CLASSES 在 settings.py 文件中正确设置
    猜你喜欢
    • 2020-01-10
    • 2021-09-30
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多