Django + Angular方法PUT和POST不允许

时间:2016-07-21 03:05:07

标签: javascript angularjs django request

我用Django / Django-Rest和AngularJS 1.4.9重构了一个项目。我的所有GET请求都正常工作,但PUT和POST请求没有。我收到“405(METHOD NOTALLOWED)”错误。

我的所有http请求都是Ajax并且工作正常,但我现在正在改为$ http并遇到麻烦。有什么问题?

app.js

'use strict';
angular.module('myapp', [], function($interpolateProvider, $httpProvider) {
    $interpolateProvider.startSymbol('{[{');
    $interpolateProvider.endSymbol('}]}');
    $httpProvider.defaults.xsrfCookieName = 'jxcsrf';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}).run(function($http) {
    $http.defaults.headers.common['Content-Type'] = "application/json";
});

UPDATE 显示django视图(但我认为这不是django问题,因为使用了ajax)

视图

class MusicAction(APIView):
    """
    Create a music instance or update the vote field in a music instance.
    """

    permission_classes = (IsAllowedOrAdminOrReadOnly,)

    def get_playlist(self, station, playlist_id):
        try:
            return Playlist.objects.get(station=station, pk=playlist_id, playing="1")
        except Playlist.DoesNotExist:
            raise ValidationError(u'Essa playlist não está em uso.')

    def get_music(self, music_id, playlist_id):
        try:
            obj = Music.objects.get(music_id=music_id, playlist_id=playlist_id)
            return obj
        except Music.DoesNotExist:
            raise ValidationError(u'Essa música já tocou ou não existe.')

    def get_object(self, station_id):
        try:
            obj = Station.objects.get(pk=station_id, is_active=True)
            self.check_object_permissions(self.request, obj)
            return obj
        except Station.DoesNotExist:
            return Response(status=404)


    def put(self, request, format=None):
        station_id = request.data.get("sid")
        station = self.get_object(station_id)
        playlist_id = request.data.get("pid")
        playlist = self.get_playlist(station, playlist_id)
        music_id = request.data.get('mid')

        music = self.get_music(music_id, playlist_id)
        vote = int(request.data.get("vote"))

        with transaction.atomic():
            total = music.vote
            music.vote = total + vote
            music.save()

            station.last_update = timezone.now()
            station.save()

            if vote > 0:
                Voting.objects.create(voted_by=request.user, music=music)
            else:
                vote = Voting.objects.get(voted_by=request.user, music=music)
                vote.delete()

            serializer = MusicSerializer(music)

            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是标题。

request fail

1 个答案:

答案 0 :(得分:0)

尝试使用django rest framework的一般视图:

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

例如,如果您想接受get并使用RetrieveUpdateAPIView:

from rest_framework import generics

class MusicAction(generics.RetrieveUpdateAPIView):
    #code...