我正在尝试使用django Rest框架编写用于将产品添加到购物车的API。我写了一个简单的serializer.py和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()),
[我的浏览视图如下所示:Just Content field.No Unit Price and Quantity field]
答案 0 :(得分:2)
你的可浏览api看起来不错。您必须将JSON对象插入内容字段并将其发布到api。你的JSON看起来像这样:
{
"product": 1,
"unit_price": "22",
"quantity": 5
}
答案 1 :(得分:1)
from rest_framework.renderers import (
HTMLFormRenderer,
JSONRenderer,
BrowsableAPIRenderer,
)
class CustomerApi(APIView):
serializer_class = CustomerSerializer
renderer_classes = (BrowsableAPIRenderer, JSONRenderer, HTMLFormRenderer)
..... give whatever methods here
您必须添加serializer_class = <your serializer>
才能在browsable api中显示表单