Django REST Framework - Serialize ForeignKey fields

In my app, users have a wall, similar to the old Facebook wall. A user is able to post comments on other users walls. I have a serializer with a base structure like this:

class UserWallCommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserWallComment
        fields = ('uid', 'uidcommenter', 'idwall', 'created', 'description')
        read_only_fields = ('uid', 'uidcommenter', 'idwall', 'created')

uid and uidcommenter are foreignkeys to the user model, idwall is the PK, and description is the comment itself.

When a comment is created/edited, uid and uidcommenter needs to be set by the backend. A user can not be allowed to change these fields.

Lets say I have the variables uid and uidcommenter in my view that is calling the serializer - how can I pass these variables along to the serializer so that a UserWallComment is created?

I have tried setting uid and uidcommenter using the SerializerMethodField (passing the PK's in the context variable), but the database says I am passing NULL PK's:

class UserWallCommentSerializer(serializers.ModelSerializer):
    uid = serializers.SerializerMethodField('setUid')
    class Meta:
        model = UserWallComment
        fields = ('uid', 'uidcommenter', 'idwall', 'created', 'description')
        read_only_fields = ('uidcommenter', 'idwall', 'created')
def setUid(self):
    return self.context['uid']

My view code (idwall is the pk of the wall):

class MemberWall(APIView):
    def post(self, request, requestUid, idwall):
        uid = request.user.uid
        serializer = UserWallCommentSerializer(data=request.DATA, context={'uid': requestUid, 'uidcommenter': uid})

        if serializer.is_valid():
            return Response(['uid'], status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


the documentation says that the SerializerMethodField is used only for representation of the object. Which means it is used only when you return your data as a response.

By default the serializer get's the request passed:

def get_serializer_context(self):
    Extra context provided to the serializer class.
    return {
        'request': self.request,
        'format': self.format_kwarg,
        'view': self

This means that you can overwrite de default save, update methods of the serializer and set the relevant fields. You should be able to access then using: self._context.request.user.uid

I didn't try this but it should work.

Need Your Help

Configuring public key of users via gitolite throws error

git gitolite

I have added the public key of a user and pushed to the server.