dev-jim
dev-jim

Reputation: 2524

How to serialize custom user model in DRF

I have made a custom user model,by referring the tutorial , this is how I serialize the new user model:

Serializers.py

from django.conf import settings
User = settings.AUTH_USER_MODEL

class UserSerializer(serializers.ModelSerializer):
    post = serializers.PrimaryKeyRelatedField(many=True, queryset=Listing.objects.all())
    class Meta(object):
        model = User
        fields = ('username', 'email','post')

Views.py

from django.conf import settings
User = settings.AUTH_USER_MODEL
class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

But when I tried to use this serializer,I get

'str' object has no attribute '_meta'

What did I do wrong?

Upvotes: 11

Views: 7341

Answers (1)

levi
levi

Reputation: 22697

Instead of

User = settings.AUTH_USER_MODEL

use

from django.contrib.auth import get_user_model
User = get_user_model()

Remember that settings.AUTH_USER_MODEL is just a string that indicates which user model you will use not the model itself. If you want to get the model, use get_user_model

Upvotes: 20

Related Questions