运行api时出现错误“方法“ POST”不允许”。我已经使用ModelViewSet和路由器 还可以在前端使用Ajax发送“ POST”请求。 我做了GET和PUT,它运行良好,但是POST-从来没有。 在app.views.py
中class PostsViewSet(viewsets.ModelViewSet):
queryset = Posts.objects.filter(is_published=True).select_related()
serializer_class = PostDetailSerializer
# permission_classes = (IsAuthor, MyPermission)
def perform_create(self, serializer):
serializer.save(author=self.request.user)
在app.serializers.py
中class PostDetailSerializer(serializers.HyperlinkedModelSerializer):
# author = serializers.ReadOnlyField(source='author.username')
author = UserInfoSerializer(read_only=True)
class Meta:
model = Posts
fields = ('url', 'id', 'title', 'text', 'created', 'author', 'last_modified', 'is_published')
在Permissions.py
中class IsAuthor(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
print(request.method)
if (request.method in permissions.SAFE_METHODS or request.user and
request.user.is_authenticated()):
return True
return obj.author == request.user
MyPermission(permissions.BasePermission)类:
allowed_methods = ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS']
def has_permission(self, request, view):
return request.method in self.allowed_methods
在urls.py
中class PostsRouter(routers.SimpleRouter):
routes = [
routers.Route(
url=r'^{prefix}{trailing_slash}$',
mapping={'get': 'list'},
name='{basename}-list',
initkwargs={'suffix': 'List'},
detail=False
),
routers.Route(
url=r'^{prefix}/{lookup}{trailing_slash}$',
mapping={'get': 'retrieve'},
name='{basename}-detail',
initkwargs={'suffix': 'Detail'},
detail=True
),
routers.Route(
url=r'^{prefix}/create/$',
mapping={'post': 'create'},
name='{basename}-create',
initkwargs={'suffix': 'Detail'},
detail=True
),
routers.Route(
url=r'^{prefix}/{lookup}/update/$',
mapping={'put': 'update'},
name='{basename}-update',
initkwargs={'suffix': 'Detail'},
detail=True
),
]
router = PostsRouter()
router.register(r'users', views.UserViewSet)
router.register(r'', views.PostsViewSet)
urlpatterns = [
url(r'', include(router.urls)),
]
请帮助!!! PS: 完整代码在github https://github.com/NikolayPogoreliy/SimpleBlog
上