我正在尝试将数据发布到Django Rest Framework API,我有一个有效的GET请求。 POST请求不起作用,并且AJAX调用的错误功能被触发。我似乎看不到为什么它不起作用,也许我的CSRF或CORS标头不正确?
main.js
$(function () {
var $items = $('#items');
var $description = $('#description');
var $price = $('#price');
$.ajax({
type: 'GET',
url: '/api',
success: function(items) {
console.log(items)
$.each(items,function(i, item){
$items.append('<li> '+ item.pk +', '+ item.Description +', '+ item.Price +'</li>');
});
},
error: function() {
alert('Error Loading Items');
}
});
$('#add-item').on('click', function() {
var order = {
description: $description.val(),
price: $price.val(),
};
$.ajax({
type: 'POST',
csrfmiddlewaretoken: "{{ csrf_token }}",
url: '127.0.0.1:8000/api/',
data: order,
success: function(newItem) {
$items.append('<li> '+ newItem.Description +', '+ newItem.Price +'</li>');
},
error: function() {
console.log(order)
}
});
});
});
models.py
class Item(models.Model):
Description = models.CharField(max_length=20)
Price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return self.Description
Serializers Views.py
class ItemListAPIView(generics.ListCreateAPIView):
lookup_field = 'pk'
queryset = Item.objects.all()
serializer_class = ItemSerializer
permission_classes = (AllowAny,)
[发布请求要求X-CSRF-TOKEN标头设置了正确的令牌-这就是get
请求正在传递的原因(我认为),但post
没有传递。
您不能在javascript文件中使用Django模板语言({{ csrf_token }}
),因为它不会呈现为实际的标记-它只会传递字符串文字'{{ csrf_token }}'
。
假设django docs,您可以在authentication is set by default的帮助下获取这样的实际令牌:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$.ajax({
type: 'POST',
headers: {
'X-CSRF-TOKEN': getCookie('csrftoken'),
'Content-Type': 'application/json'
},
url: '127.0.0.1:8000/api/',
data: order,
success: function (newItem) {
$items.append('<li> ' + newItem.Description + ', ' + newItem.Price + '</li>');
},
error: function () {
console.log(order)
}
});