I'm recently approaching drf and I want to create a system that returns a user's information. Among the various fields, the user has an avatar which should return the URL of the photo where it is saved. The problem is that I get a relative path instead of an absolute path. Below I attach the code of my app.
models.py
def get_upload_path(instance, filename):
return os.path.join('images' , 'avatar' , str(instance.pk),filename)
class CustomUser(AbstractUser):
username = models.CharField(max_length=50, unique=True)
email = models.EmailField(_('email address'), unique=True)
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
avatar = models.ImageField(upload_to=get_upload_path, blank=True, null=True,)
is_active = models.BooleanField(default=True)
is_verified = models.BooleanField(default=False)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
last_login = models.DateTimeField(_('last login'), auto_now=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.username
serializers.py
class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = ['id','username','email','name','surname','avatar',]
views.py
class CustomUserAPIView(APIView):
def get(self,request):
serializer = CustomUserSerializer(request.user)
return Response(serializer.data)
what I get is this:
{
"id": 1,
"username": "admin",
"email": "[email protected]",
"name": "John",
"surname": "Test",
"avatar": "/media/images/avatar/1/photo.JPG"
}
but what I need to get is this
{
"id": 1,
"username": "admin",
"email": "[email protected]",
"name": "John",
"surname": "Test",
"avatar": "http://127.0.0.1:8000/media/images/avatar/1/photo.JPG"
}
how can I solve it? Thanks in advance for the reply
Use the
urlattribute available on FileFields (which ImageFields also are); you can get at it neatly withfield.source.