不允许使用DRF + Ajax方法“ POST”。视图集+路由器

时间:2018-08-01 15:09:46

标签: django python-3.x django-rest-framework django-rest-viewsets

运行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

0 个答案:

没有答案