Django休息:AJAX Post无法正常工作,400响应

时间:2017-04-03 14:41:05

标签: javascript ajax django django-rest-framework

我是DRF和Ajax的新手,我的序列化代码

class CartItem(models.Model):
    cart_id = models.CharField('Cart ID', max_length=50)
    shop =   models.ForeignKey(Shop)
    date_added = models.DateTimeField('Added on', auto_now_add=True)
    quantity = models.IntegerField('Quantity', default=1)
    product = models.ForeignKey(Products,)
    bylist = models.CharField('Item', max_length=150, null=True, blank=True)
    image = models.ImageField('Photo', upload_to='order/%Y',null=True, blank=True)
    image_thumb        =   ImageSpecField(source='image',
                                            processors=[Transpose(),ResizeToFill(200, 200)],
                                            format='JPEG',
                                        options={'quality': 95})
    comment = models.CharField('Comment', max_length=150, null=True, blank=True)

class ShopSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Shop
        fields = "__all__"

class ProductsSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Products
        fields = "__all__"          

class CartItemSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = CartItem
        exclude = ('cart_id',)

尝试使用以下json测试POST调用,但获得400 - Bad请求。试过很多不同的方法,但无法解决。请帮忙

function create_post(shop, pd) {    
    jQuery.ajax({
            type: "POST",
            beforeSend: function (request)
            {
                request.setRequestHeader("X-CSRF-TOKEN", "${_csrf.token}");
            },
            url: "/api/cart/",
            data: JSON.stringify({"shop":"http://127.0.0.1:8000/api/shop/1/","product":"http://127.0.0.1:8000/pd/10/",}),
            //console.log(data);
            success : function(result) {
            console.log("Success!");
   }
});
}

还与json一起尝试:

var json = '{"shop":'+1+',"product":'+2+',"quantity": null,"bylist": "","image": null,"comment": "",}'

编辑:我的网址;

url(r'^api/cart/$', views.CartItemList.as_view(), name='cartitem-list'),
    url(r'^api/cart/(?P<pk>\w+)/$', views.CartItemDetail.as_view(), name='cartitem-detail'),
    url(r'^api/shop/(?P<pk>\w+)/$', views.ShopDetail.as_view(), name='shop-detail'),
    url(r'^api/pd/(?P<pk>\w+)/$', views.ProductsDetail.as_view(), name='products-detail'),

视图:

class CartItemList(generics.ListCreateAPIView):
    model = CartItem
    queryset = CartItem.objects.all()
    serializer_class = CartItemSerializer
    permission_classes = [
        permissions.AllowAny
    ]
    def perform_create(self, serializer):
        print 'create_view_invoked'
        if self.request.session.get(CART_ID_SESSION_KEY,'') == '':
            self.cart_id = ''
            characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()'
            cart_id_length = 50
            for y in range(cart_id_length):
                self.cart_id += characters[random.randint(0, len(characters)-1)]
            print self.cart_id
            self.request.session[CART_ID_SESSION_KEY] = self.cart_id
        print self.request.session[CART_ID_SESSION_KEY]
        serializer.save(cart_id=self.request.session[CART_ID_SESSION_KEY])

    def get_queryset(self):
        print 'get_view_invoked'
        if self.request.session.get(CART_ID_SESSION_KEY,'') == '':
            self.cart_id=''        
        else:
            self.cart_id = self.request.session[CART_ID_SESSION_KEY]
            print self.cart_id
        return CartItem.objects.filter(cart_id=self.cart_id)

忘记提及,它可以直接从DRF API UI(http://127.0.0.1/api/cart/)工作。

我没有在django中看到任何错误,只有400显示在日志中。

[03/Apr/2017 19:28:04] "POST /api/cart/ HTTP/1.1" 400 74
[03/Apr/2017 19:28:07] "POST /api/cart/ HTTP/1.1" 400 74
[03/Apr/2017 19:28:09] "POST /api/cart/ HTTP/1.1" 400 74

1 个答案:

答案 0 :(得分:1)

HTTP 400Bad Request,这意味着Django无法理解请求。

尝试添加:

  dataType: "json",
  contentType: "application/json"

现在Django会知道您发布了json 这就是你要找的东西。