问题描述:
- 用django编写一个接口,用到django-rest-framwork的api_view装饰器
代码如下:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(["GET"])
def hello_world(request):
return Response({"message": "hello world!"})
浏览器访问报错如下:
Cannot apply DjangoModelPermissions on a view that does not set
.queryset
or have a.get_queryset()
method.
原因:
进入rest-farmwork设置了只读权限
解决方法:
在工程settings中找到
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'
]
}
将其变更为默认权限:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissions'
]
}
google浏览器再次访问接口
火狐访问:
最终解决方法:
不设置权限,可以删掉
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
]
}
或者在接口实现方法中再添加一个装饰器
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import permissions
@api_view(["GET"])
@permission_classes((permissions.AllowAny,))
def hello_world(request):
return Response({"message": "hello world!"})
再次访问接口,成功。