Reputation: 9732
This is probably a very simple question, but I cant seem to solve it.
I have a ModelSerializer like so:
class UserSerializer(serializers.ModelSerializer):
# http -v POST http://127.0.0.1:8000/user/user-list/ email="[email protected]" password="123"
def create(self, validated_data):
user = UserModel.objects.create(
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.is_active = False
user.save()
return user
class Meta:
model = UserModel
fields = (
'email',
'password',
'is_active',
'company',
'name',
)
read_only_fields = ('is_active',)
extra_kwargs = {
'password': {'write_only': True},
}
The corresponding view looks like this:
class UserDetail(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request):
try:
user = request.user
serializer = UserMailSerializer(user)
print(serializer.data)
return Response(serializer.data, status=status.HTTP_200_OK)
except UserModel.DoesNotExist:
return Response(serializer.data, status=status.HTTP_401_UNAUTHORIZED)
When I sent a GET request the serializer.data will only return the 'email' address (I am using a custom User Model with the email as primary identification).
I want to return all the fields that are not specified as write_only. How Do I achieve this?
Upvotes: 0
Views: 43
Reputation: 88619
You are using UserMailSerializer
serializer class in your views, which may be the wrong one. Use UserSerializer
serializer instead
class UserDetail(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request):
try:
user = request.user
serializer = UserSerializer(user) # change is here <<<<<
print(serializer.data)
return Response(serializer.data, status=status.HTTP_200_OK)
except UserModel.DoesNotExist:
return Response(serializer.data, status=status.HTTP_401_UNAUTHORIZED)
Upvotes: 1