I want any user to be able to create their own products using my RESTful API. For this purpose, I created a view that inherits ListCreateAPIView. The problem is that the user should only create products that belong to him, so when the product model instance was created, I wanted the owner of the field to match the authenticated user.
Here is my product model
class Product(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=30)
Obviously my serializer:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = models.Product
and my opinion:
class ProductView(generics.ListCreateAPIView):
queryset = models.Product.objects.all()
serializer_class = serializers.ProductSerializer
permission_classes = (IsAuthenticatedOrReadOnly,)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
, "initial_data", QueryDict, inmutable. - Python, "owner", (, {'name': ['MyName']}), , , .