Skip to content Skip to sidebar Skip to footer

Django Rest Framework Currentuserdefault() With Serializer

I have been trying for a while now to add an 'owner' field to my models. I have looked at other questions but I still have had no luck. Ideally when a new note is created, the curr

Solution 1:

I have a clean routine for this kind of situations, that I'll explain. first of all, CurrentUserDefault is not doing something magical, it is just returning the user of the request that we previously gave to the serializer (generic views pass the request to the serializer by calling get_serializer, since you are using generics you are doing fine).

but for our purpose, we'll write a new customized CurrentUserDefault, that it'll return the id of the user:

classCurrentUserDefault(object):defset_context(self, serializer_field):
        self.user_id = serializer_field.context['request'].user.id

    def__call__(self):
        returnself.user_id

    def__repr__(self):
        return unicode_to_repr('%s()' % self.__class__.__name__)

now we are just gonna use this CurrentUserDefault and fill the owner_id field of the NoteSummarySerializer, I suggest you use serializers.HiddenField, cause according to the drf doc:

A field class that does not take a value based on user input, but instead takes its value from a default value or callable.

This field will be present in validated_data but will not be used in the serializer output representation.

so it only gets its value from default or callable, so it's not Changeable by user input, and also it will not be used in the serializer output representation. seems great, right?

we just add this field to the serializer:

classNoteSummarySerializer(serializers.ModelSerializer):
    owner_id = serializers.HiddenField(default=CurrentUserDefault())

    classMeta:
        model = Note
        fields = (
            'pk',
            'title',
            'containerId',
            'created',
            'updated',
            'owner_id', ### dont forget to add it to the fields.
        )

then for final step, since we used owner_id fo filling the the owner, the name owner is available for other uses. in this case i think make it CharField and give owner.username (or anything you want) to its source and make its readonly True, so our Serializer finnally gonna be like:

classNoteSummarySerializer(serializers.ModelSerializer):
    owner_id = serializers.HiddenField(default=CurrentUserDefault())
    owner = serializers.CharField(source='owner.username', read_only=True)

    classMeta:
        model = Notefields= (
            'pk',
            'title',
            'containerId',
            'created',
            'updated',
            'owner_id',
            'owner'
        )

Post a Comment for "Django Rest Framework Currentuserdefault() With Serializer"