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