Skip to content Skip to sidebar Skip to footer

Post Api Using Token From Header

I am posting using an API to create a new entry in the model Movie. Using headers, I would like to be able to POST so the OWNER is the user who has posted it. The users token is se

Solution 1:

You can set user using context['request'] of form, which is provided by default in GenericAPIViews. http://www.django-rest-framework.org/api-guide/serializers/#including-extra-context

def create(self, validated_data):
    tags_data = validated_data.pop('tag')
    owner = self.context['request'].user
    movie = Movie.objects.create(owner=owner, **validated_data)
    for tag_data in tags_data:
        tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])
        if tag_qs.exists():
            tag = tag_qs.first()
        else:
            tag = Tag.objects.create(**tag_data)
        task.tag.add(tag)
    return movie

Post a Comment for "Post Api Using Token From Header"