Django Rest Framework — Creating objects with user

(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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s