Home > Software engineering >  What should i write in "category": to create a post that belongs to a specific category li
What should i write in "category": to create a post that belongs to a specific category li

Time:06-06

Since i created 2 categories in the admin panel like this:

image

but when i want to post this json it gives my this error:

[
    {
        "category": [
            "Incorrect type. Expected pk value, received str."
        ]
    },
    {
        "category": [
            "Incorrect type. Expected pk value, received str."
        ]
    }
]

json:

[
  {
    "image": "https://a ",
    "description": "J t",
    "price": "USD 8.70",
    "buy": "https:// 6d7",
    "category": "foods"
  },
  {
    "image": "https:// ",
    "description": " elf",
    "price": " 65",
    "buy": "https://s.c D",
    "category": "foods"
  }

]

image

What should i write in "category": to create a post that belongs to a specific category like foods?

models:

class category(models.Model):

    name=models.CharField(max_length=255, db_index=True)

    def __str__(self):
        return self.name

class product(models.Model):
     
    category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) 
    image=models.CharField(max_length=500)
    description=models.CharField(max_length=500)
    price=models.CharField(max_length=50)
    buy=models.CharField(max_length=100)
 

views:

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

    def create(self, request):
        serialized = productSerializer(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)

    @action (detail=False , methods=['post']) 
    def delete(self,request):
        product.objects.all().delete()
        return Response('success')
def home(request):
    
    return render(request,'home.html',{'p':category.objects.all()})

def foods(request):
    
    return render(request,'foods.html',{'p':category.objects.all()})

CodePudding user response:

you need to send pk >> primiary key or id of Category object, for your example, pk 1 is home, and pk 2 is foods

[
  {
    "image": "https://a ",
    "description": "J t",
    "price": "USD 8.70",
    "buy": "https:// 6d7",
    "category": 1
  },
  {
    "image": "https:// ",
    "description": " elf",
    "price": " 65",
    "buy": "https://s.c D",
    "category": 2
  }

]
  • Related