您没有权限在Django中访问api时执行此操作

时间:2018-07-20 06:55:46

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

我正在尝试使用Django rest框架在Django应用中添加自定义权限。我创建了一个API n在邮递员中对其进行了测试,对于经过身份验证的用户来说效果很好。但是,当我访问详细信息视图时,它不显示详细信息。例如,当我访问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',
)
}

....

1 个答案:

答案 0 :(得分:3)

这是由于您的自定义权限,您试图访问实例(所有者为pk = 1)时,所有者不是您当前正在使用的用户。

检查该地方的所有者。

您还可以只删除视图中的permissions.IsAuthenticated,因为您已经将其放入默认权限类中。