Home > database >  what should i do to be able to post multiple contents in my code in django rest framework?
what should i do to be able to post multiple contents in my code in django rest framework?

Time:05-31

This is my serializers.py:

from rest_framework import serializers
from .models import product
 


class productSerializer(serializers.ModelSerializer):
    class Meta:
        model= product
        fields="__all__"
 

views.py:

from django.shortcuts import render
from .models import *
from rest_framework import viewsets
from .serializers import productSerializer
from rest_framework.parsers import JSONParser

class productviewset(viewsets.ModelViewSet):
    queryset=product.objects.all()
    serializer_class=productSerializer 
    

When i want to post multiple contents like this:

[
  {
     "Number": 1,
     "name": "1005001697316642",
     "image": "https://",
     "description": "fffffffff",
     "price": "USD 23.43",
     "buy": "https://"
  },
  {
     "Number": 2,
     "name": "1005002480978025",
     "image": "https://",
     "description": "dffdfdddddddddddddd",
     "price": "USD 0.89",
     "buy": "https://"
   }
 ]

I get this error:

HTTP 400 Bad Request

Allow: GET, POST, HEAD, OPTIONS

Content-Type: application/json

Vary: Accept

{ "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] }

what should i do to be able to post multiple contents?

CodePudding user response:

You have to overwrite the create method to allow multiple objects, So we will overwrite it in the scope of the class that inherits ModelViewSet, as shown below:

def create(self, request):
serialized = MovieTicketSerializer(data=request.data, many=True)
if serialized.is_valid():
    serialized.save()
    return Response(serialized.data, status=status.HTTP_201_CREATED)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
  • Related