gpt4 book ai didi

python - django rest framework 错误 Cannot apply DjangoModelPermissions on a view that does not set `.queryset` or have a `.get_queryset()` method

转载 作者:太空狗 更新时间:2023-10-30 01:06:33 35 4
gpt4 key购买 nike

我正在使用 django 1.9.5 和 rest framework 3.x(DRF)。我刚刚遵循了官方 django rest 框架的教程,你可以说它是从 DRF 开始的,我写了以下 View , urls 以查看 api 如何使用 DRF,

观看次数

class DepartMentList(APIView):
"""
List of all departments or create a department
"""

def get(self, request, format=None):
departments = Department.objects.all()
serializer = DepartmentSerializer(departments)
return Response(serializer.data)

def post(self, request, format=None):
serializer = DepartmentSerializer(data=request.data)

if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer._errors, status=status.HTTP_400_BAD_REQUEST)

网址

from django.conf.urls import url

from rest_framework.urlpatterns import format_suffix_patterns

from organizations import views

urlpatterns = [
url(r'^departments/$', views.DepartMentList.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

这是 setting.py,我在其中为 DEFAULT_PERMISSION_CLASSES 添加了以下 rest framework 字典

REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]

现在,当我为部门 运行端点 以查看部门列表时,出现以下错误,

'Cannot apply DjangoModelPermissions on a view that '
AssertionError: Cannot apply DjangoModelPermissions on a view that does not set `.queryset` or have a `.get_queryset()` method.

究竟是什么导致了错误?我已经调查过了,但无法弄清楚。

更新

class DepartMentDetail(APIView):
"""
Retrieve, update or delete a department instance.
"""

def get_object(self, pk):

try:
return Department.objects.get(pk=pk)
except Department.DoesNotExist:
raise Http404

def get(self,request,pk,format=None):

department = self.get_object(pk)
serializer = DepartmentSerializer(department)
return Response(serializer.data)

def put(self,request,pk,format=None):
department = self.get_object(pk)
serializer = DepartmentSerializer(department,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def delete(self, request, pk, format=None):
department = self.get_object(pk)
department.delete()
return Response(status=status.HTTP_204_NO_CONTENT)

最佳答案

DjangoRestFramework 要求您设置queryset 类参数或在您的 View 上实现get_queryset 方法。它在应用权限类时检查它。因为 DjangoModelPermissionsOrAnonReadOnly 有如下所示的 has_permission 方法,这个方法检查你的 View 是否有 queryset 变量或 get_queryset 方法.

def has_permission(self, request, view):
# Workaround to ensure DjangoModelPermissions are not applied
# to the root view when using DefaultRouter.
if getattr(view, '_ignore_model_permissions', False):
return True

if hasattr(view, 'get_queryset'):
queryset = view.get_queryset()
else:
queryset = getattr(view, 'queryset', None)

assert queryset is not None, (
'Cannot apply DjangoModelPermissions on a view that '
'does not set `.queryset` or have a `.get_queryset()` method.'
)

perms = self.get_required_permissions(request.method, queryset.model)

return (
request.user and
(request.user.is_authenticated() or not self.authenticated_users_only) and
request.user.has_perms(perms)
)

如您所见,has_permission 方法为 queryset 变量生成 assert您的 View 应如下所示

class DepartMentList(APIView):
"""
List of all departments or create a department
"""
queryset = Department.objects.all()

def get(self, request, format=None):
serializer = DepartmentSerializer(self.queryset)
return Response(serializer.data)

def post(self, request, format=None):
serializer = DepartmentSerializer(data=request.data)

if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer._errors, status=status.HTTP_400_BAD_REQUEST)

P.S 使用http://www.django-rest-framework.org/api-guide/generic-views/它更干净))

关于python - django rest framework 错误 Cannot apply DjangoModelPermissions on a view that does not set `.queryset` or have a `.get_queryset()` method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36442713/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com