I have an api where users can create different objects. If the user is part of the staff, he can create the object with all the values he wants. However, if the user is not part of the staff, I want to force the value of a particular field.
I added the following code to a viewset that works well:
@swagger_auto_schema(responses={201: CategoryProductSerializer})
def create(self, request, *args, **kwargs):
if not self.request.user.is_staff:
request.data['client']=request.user.profil.client.pk
print(request.data)
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)
def perform_create(self, serializer):
serializer.save()
How can I "generalize" this to all my modelviewsets? The important part of this create that must be common to all my viewsets is :
if not self.request.user.is_staff:
request.data['client']=request.user.profil.client.pk