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]
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With