gpt4 book ai didi

javascript - 不允许 Django + Angular 方法 PUT 和 POST

转载 作者:行者123 更新时间:2023-11-28 05:46:19 24 4
gpt4 key购买 nike

我用 Django/Django-Rest 和 AngularJS 1.4.9 重构了一个项目。我的所有 GET 请求都工作正常,但 PUT 和 POST 请求却不能。我收到“405(不允许使用方法)”错误。

我所有的 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";
});

更新显示 django View (但我认为不是 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

最佳答案

尝试使用 django Rest 框架的通用 View 之一:

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

例如,如果您想接受 get 和 put,请使用 RetrieveUpdateAPIView:

from rest_framework import generics

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

关于javascript - 不允许 Django + Angular 方法 PUT 和 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com