1

I am newbie to DRF and Ajax, my serializer code

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',)

Trying to test the POST call with below json, but getting 400 - Bad request. Tried many different ways but couldn't solve. Please help

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!");
   }
});
}

Also Tried with json:

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

EDIT: my url conf;

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'),

view:

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)

Forgot to mention, it is working fine directly from DRF API UI (http://127.0.0.1/api/cart/).

I am not seeing any errors in django, only 400 is shown in log.

[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
user3369417
  • 358
  • 1
  • 4
  • 17

1 Answers1

1

HTTP 400 is Bad Request which means that Django is unable to understand the request.

Try adding:

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

Now Django will know that you are posting json This is what you are looking for.

xssChauhan
  • 2,728
  • 2
  • 25
  • 36
  • Thank you Shikhar, I added the above, also changed the related fields with full url ( data: JSON.stringify({"shop":"/api/shop/2/","product":"/api/pd/10/",}), ) It is fixed now. Thanks a lot. – user3369417 Apr 04 '17 at 03:53
  • If the answer solved the problem please refer to [this](http://stackoverflow.com/help/someone-answers) – xssChauhan Apr 04 '17 at 03:57
  • Thank you Shikhar, I added the above, also changed the related fields with full url ( data: JSON.stringify({"shop":"/api/shop/2/","product":"/api/pd/10/",}), ) It is fixed now. Thanks a lot. Now I am looking for getting cart details (count and recent items added) in the template, any clue, server side count or client side count and how to handle items removed. Thanks – user3369417 Apr 04 '17 at 04:04