在Django Rest Framework上使用viewsets进行POST返回“405 - METHOD POST NOT NOTOWED”

时间:2016-09-15 22:17:25

标签: django django-rest-framework

我正在尝试为我的IOS应用程序创建一个HiScore模块。

我坚持使用POST(可能与PUT有相同的问题,但不确定)部分,我在Postman中得到405。 列表和详细信息工作得很好,因此模型,序列化程序或视图没有问题,只是我猜想在某处添加权限

视图

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class GameViewSet(viewsets.ModelViewSet):
    queryset = HiScore.objects.all()
    serializer_class = GameSerializer

class GameTypeViewSet(viewsets.ModelViewSet):
    queryset = HiScore.objects.all()
    serializer_class = GameTypeSerializer

class GameLevelViewSet(viewsets.ModelViewSet):
    queryset = HiScore.objects.all()
    serializer_class = GameLevelSerializer

class HiScoreViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny,]
    queryset = HiScore.objects.all()
    serializer_class = HiScoreSerializer

serialisers.py

class HiScoreSerializer(ModelSerializer):
image = SerializerMethodField()
class Meta:
    model = HiScore
    fields = ("user", "game", "gameType", "gameLevel", "points", "image")

def get_image(self, obj):
    try:
        profile = UserProfile.objects.get(user=obj.user)
        return profile.image.url
    except:
        return None

urls.py

router = DefaultRouter()
router.register(prefix='hiscores', viewset=HiScoreViewSet)

urlpatterns = router.urls

1 个答案:

答案 0 :(得分:1)

根据documentation,我认为您在视野中遗失as_view。试试这个:

观点:

hiscores = HiScoreViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

在网址中:

from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = format_suffix_patterns([
    url(r'^hiscores/$', hiscores, name='hiscores')
])

http://www.django-rest-framework.org/api-guide/viewsets/