1

I am getting error 'Method "POST" not allowed' while running the api. I have use ModelViewSet and Routers Also use Ajax on front-end to send "POST"-request. I did GET and PUT, and it's work perfectly, but POST - never. in 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)

in 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')

in 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

class MyPermission(permissions.BasePermission):

allowed_methods = ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS']

def has_permission(self, request, view):
    return request.method in self.allowed_methods

in 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)),
]

Please help!!! PS: Full code is on github https://github.com/NikolayPogoreliy/SimpleBlog

4

0 回答 0