You need a little editing in your serializer:
class PostSerializer(serializers.ModelSerializer): class Meta: model = Post def save(self): user = self.context['request'].user title = self.validated_data['title'] article = self.validated_data['article']
Here is an example using view blending models. In the create method, you can find the correct way to call the serializer. The get_serializer method correctly populates the context dictionary. If you need to use a different serializer defined in the set of views, see the update Method on how to start the serializer using the context dictionary, which also passes the request object to the serializer.
class SignupViewSet(mixins.UpdateModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): http_method_names = ["put", "post"] serializer_class = PostSerializer 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) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() kwargs['context'] = self.get_serializer_context() serializer = PostSerializer(instance, data=request.data, partial=partial, **kwargs) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data)
cgl Jul 19 '19 at 11:02 2019-07-19 11:02
source share