Post API using Token from header

2019-09-11 13:41发布

问题:

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 sent via headers.

models.py

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

class Movie(models.Model):
    title = models.CharField("Title", max_length=10000, blank=True)
    tag = models.ManyToManyField('Tag', blank=True)
    created = models.DateTimeField("Created", auto_now_add=True)
    owner = models.ForeignKey('auth.User', blank=True, null=True)

Views.py

class OwnerFilterBackend(filters.BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)

class AllViewSet(viewsets.ModelViewSet):
    filter_backends = (OwnerFilterBackend,)
    queryset = Movie.objects.order_by('-created',).exclude(deleted=True).exclude(typetask=2)
    serializer_class = AllSerializer

Serializers.py

class AllSerializer(serializers.ModelSerializer):
    tag = TagSerializer(many=True, read_only=True)
    class Meta:
        model = Movie
        fields = ('title', 'mail', 'pk', 'tag', 'info', 'created', 'deleted', 'status', 'typetask')

    def create(self, validated_data):
        tags_data = validated_data.pop('tag')
        movie = Movie.objects.create(**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

回答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