I am working on my Django (DRF) app.
I have a user avatar
class CustomUser(AbstractBaseUser, PermissionsMixin):
avatar = models.ImageField(upload_to='avatars/', blank=True)
...
I want to serialize avatar field:
class CustomUserSerializer(serializers.ModelSerializer):
avatar = serializers.FileField(use_url=False, required=False)
class Meta:
model = CustomUser
fields = [
'avatar',
...
]
Current result is "avatar": "avatars/ZZZ.png"
How can I get "avatar": "media/avatars/ZZZ.png"
??? (what is the proper way)
Saved file location is http://localhost:6060/media/avatars/<file_name>.png
CodePudding user response:
I haven't worked with image field serialized. Below is my solution, and don't know if there is a better way.
You can override the to_representation
method of your serializer to achieve it as shown below.
class CustomUserSerializer(serializers.ModelSerializer):
avatar = serializers.FileField(use_url=False, required=False)
class Meta:
model = CustomUser
fields = [
'avatar',
...
]
def to_representation(self, instance):
resp = super().to_representation(instance)
resp['avatar'] = f'media/{resp["avatar"}'
return resp