(Originally posted July 30, 2013)
I recently ran into a little hitch when working with Django Rest Framework. Since the model that I was working with had to be attached to a user, I needed to have some way to set the member before the serializer was saved, but after validation. The solution turns out to be very similar to what you do in a form.
def post(self, request, format=None): serializer = GoalSerializer(data=request.DATA) if serializer.is_valid(): serializer.object.member = self.request.user.get_profile() serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Very simple and working solution. There should be another way to do this using the pre_save method that comes with subclassing the view with the DRF Create mixin, but I wasn’t able to get that working right now. At the moment, I just wanted something that worked so I can keep developing and moving forward. The other solution is less hack-ish, so when I have time to go back, I’ll update this with the “correct” answer.