There are two models: Product
and Picture
. Each Product
can have several Picture
s. I have questions when I want to create a Product using POST. How to POST a nested object containing a ImageField list?
The Product
model is:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=50)
description = models.TextField(blank=True)
The Picture
model is:
class Picture(models.Model):
product = models.ForeignKey(Product, related_name='pictures')
path = models.ImageField(null=False, upload_to='product_pic')
description = models.CharField(max_length=255, null=True, blank=True)
main = models.BooleanField()
I write the serializer.py as follow:
class PictureSerializer(serializers.ModelSerializer):
class Meta:
model = Picture
fields = ('path', 'description', 'main')
class ProductSerializer(serializers.ModelSerializer):
pictures = PictureSerializer(many=True, required=False)
class Meta:
model = Product
fields = ('product_id', 'product_name', 'pictures', 'description')
The view that I am using is:
class ProductEnum(generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = (IsAuthenticated, )
def post(self, request, format=None):
serializer = ProductSerializer(data=request.DATA, files=request.FILES)
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)
I am registering it in the urls as:
url(r'^api/products/$', views.ProductEnum.as_view()),
The questions are:
- How could I test this POST api as
django-rest-framework
tells me that "Lists are not currently supported in HTML input" - How to use JSON to POST a
Product
resources with multiplePictures
. OR I must use multipart parser. - How to write cURL command?