Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fields not appearing for POST API browsable view - django Rest Framework

I am trying to write API for add product to shopping cart, using django Rest framework. I wrote a simple serializer.py and view.py.

model.py:

class Product(models.Model):
    title = models.CharField(max_length=100,unique=True)
    description = models.TextField()
    image_url = models.URLField(max_length=200)
    price = models.DecimalField(max_digits=8,decimal_places=2)
    date_available = models.DateField
class LineItem(models.Model):
    product = models.ForeignKey(Product)
    unit_price = models.DecimalField(max_digits=8,decimal_places=2)
    quantity = models.IntegerField()

serializers.py

class LineItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = LineItem
        fields = ('product', 'unit_price', 'quantity')

    def product(self, instance):
        return instance.product.title

views.py

class RESTforCart(APIView):
    def post(self, request, *args, **kwargs):
        #print request.POST['product']
        product = Product.objects.get(id=request.POST['product'])
        cart = request.session['cart']
        cart.add_product(product)
        request.session['cart'] = cart
        lists=request.session['cart'].items 
        serializer = LineItemSerializer(lists,many=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def get(self, request, *args, **kwargs):
    lists=request.session['cart'].items 
    serializer = LineItemSerializer(lists,many=True)
    return Response(serializer.data)

urls.py

(r'^shoppinglists2/$', RESTforCart.as_view()),

[My browsable view looks like this:Just Content field.No Unit Price and Quantity field]

enter image description here

like image 464
Yuejiao Hui Avatar asked Mar 29 '16 23:03

Yuejiao Hui


2 Answers

from rest_framework.renderers import (
                                        HTMLFormRenderer, 
                                        JSONRenderer, 
                                        BrowsableAPIRenderer,
                                    )

class CustomerApi(APIView):

    serializer_class = CustomerSerializer
    renderer_classes = (BrowsableAPIRenderer, JSONRenderer, HTMLFormRenderer)

   ..... give whatever methods here 

you have to add serializer_class = <your serializer> in order to show the forms in browsable api

like image 180
Thameem Avatar answered Oct 12 '22 23:10

Thameem


Your browsable api looks OK. You have to insert a JSON object into the content field and post that to the api. A JSON for you could look like this:

{
   "product": 1,
   "unit_price": "22",
   "quantity": 5
}
like image 45
ilse2005 Avatar answered Oct 13 '22 01:10

ilse2005