view raw
Ycon Ycon - 6 months ago 33
Python Question

Filter API request according header auth token

I would like to filter the objects according to the token header which gets sent with the GET requests.

My request is sending the token in the header (

get curl -H "Authorization: Token 3f3f3fzzz"

The code below returns no results (just an empty array- no error). I am unable to determine where my request object headers are.

My guess is that I need some middleware function to mutate the response and put the user object in it too.

class AllViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.order_by('-created',)
serializer_class = AllSerializer
def get_queryset(self):
Movie.objects.filter(owner = self.request.user)

I tried some debugging after the def_queryset (using
import pdb; pdb.set_trace()


Here are other parts of my code which may be relevant.

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

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)

'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),



You can write custom filter backend

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

class AllViewSet(viewsets.ModelViewSet):
    filter_backends = (OwnerFilterBackend,)