我想我会在这里问这个问题,因为我不太确定我会错在哪里。我正在尝试使用Django Rest框架类通过AJAX执行POST请求。但是,每当事件触发时,我都会收到以下错误:
OST http://127.0.0.1:8000/api/uservenue/ 400 (Bad Request)
这是堆栈跟踪中显示的内容:
{"list":["This field is required."],"venue":["This field is required."]}
上下文
我试图做到这一点,当用户单击“添加到列表”按钮时,它会向用户定义的列表发送一个cafeName(以及最终的其他详细信息)。
我想知道是否有人可以看看我的代码,并给我一些指导,我哪里出了问题?
代码
以下是相关模型:
class UserVenue(models.Model):
venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT)
list = models.ForeignKey(UserList, on_delete=models.PROTECT)
Here is the relevant serializer.py
class UserVenueSerializer(serializers.ModelSerializer):
class Meta:
model = UserVenue
fields = ['list', 'venue']
这里是相关的网址
router = DefaultRouter() #need help understanding router register
router.register('userlist', views.UserList)
router.register('uservenue', views.UserVenue)
以下是相关观点。派克
class UserVenue(viewsets.ModelViewSet):
serializer_class = UserVenueSerializer
queryset = UserVenue.objects.all()
@ensure_csrf_cookie
def get_queryset(self):
cafeName = self.request.GET.get('cafeName', None)
print(cafeName)
return UserVenue.objects.all()
最后,这里是包含CSRF代码的ajax调用。
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: "POST",
url : '/api/uservenue/',
//dataType: "json", //I tried using this and commenting it out and it made no diff.
//contentType: "application/json", //I tried using this and commenting it out and it made no diff.
data: {
'cafeName': cafeName,
'list_id': 1,
'csrfmiddlewaretoken': document.querySelector('input[name="csrfmiddlewaretoken"]').value,
},
success: function(data){
//$("user-list").html(data);
console.log('User clicked: ' + data)
},
failure: function(errMsg) {
alert(errMsg);
}
});
我不确定这是Ajax中的错误还是我的观点中的错误?
谢谢
原来我在跟踪一个变量。我已经导入了UserVenue,并试图命名类UserVenue,这导致了整个问题。
重命名为views.py类到UserVenueViewset修复了它。
让我们从一个简单的模式开始,我们可以深入到需要的地方:
首先,在js文件中,您需要执行以下操作:
// js function is executed when button is clicked:
function add_to_list() {
// execute ajax request:
$.ajax({
url : 'add_to_list',
method : 'POST',
data : {
csrfmiddlewaretoken: 'the_csrf_token',
cafe_name : 'the_cafe_name',
...
},
success: add_to_list_success,
});
} $('#button-id').click(add_to_list);
// executes on successfully contacting backend:
function add_to_list_success(response) {
// unpack response (context variable from view function)
data = response.data;
...
}
那么,在你看来。你可以这样做:
from django.http import HttpResponse
import json
def add_to_list(request):
# unpack POST data:
cafe_name = request.POST['cafe_name']
...
# conduct other logic:
...
# pack context:
context = json.dumps({
'data' : 'some_data'
})
return HttpResponse(context)
当然,不要忘记将视图函数路由到urls.py中的add_to_listURL