Develoweb Co
Develoweb Co

Reputation: 41

request.user on AbstractUser gives AnonymousUser TypeError

Calling request.user on AbstractUser model gives TypeError 'AnonymousUser' object is not iterable.

I created an abstract user model as such:

class User(AbstractUser):
    username            = models.CharField(blank=True, null=True, max_length=30)
    email               = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD      = 'email'
    REQUIRED_FIELDS     = ['username', 'first_name', 'last_name']

    def __str__(self):
        return "{}".format(self.email)

I added JSON Web Tokens to my User model. I want to get the details of the current user when I go to a particular URL. To do this, I tried this in views.py:

@api_view(['GET'])
def getUserProfile(request):
    user = request.user
    serializer = UserSerializer(user, many=True)
    return Response(serializer.data)

And this in serialisers.py

from django.conf import settings
User = settings.AUTH_USER_MODEL

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

Now, when I go to the url where this view is called from, I get TypeError 'AnonymousUser' object is not iterable. I think this is because request.user does not recognise my AbstractUser. This problem occurs even when I am logged in. How do I fix this?

Upvotes: 0

Views: 75

Answers (1)

Safiul Kabir
Safiul Kabir

Reputation: 164

In your views.py, you've set serializer = UserSerializer(user, many=True). By setting many=True, you tell DRF that queryset contains multiple items. But here user is a single object. This is what causing the exception. Try removing that part like this:

serializer = UserSerializer(user)

Upvotes: 2

Related Questions