save url in imagefield and read full url

hi this is image filed in my model :
profile_picture = models.ImageField(
upload_to=‘users/profile_pictures’, null=True, blank=True)

when my users login with social networks i save image url in image filed like this : http://example.com/image.png

but when i want to see this image url in my api show me like this localhost:/8000/media/http://…

i want to check if http in my image field give me full and correct url or user upload a picture give me the media url like localhost:8000/media/userimage.png

how can do this ?

this is mt serializer but not work :

def get_profile_picture(self, obj):
    profile_picture = obj.profile_picture
    if profile_picture and ('http://', 'https://') in  profile_picture:
        return return profile_picture
    elif profile_picture:
        # If it's a local path, prepend it with the media URL
        return self.context['request'].build_absolute_uri(profile_picture.url)
    else:
        return None

I’m not sure I understand what the source and destinations are of these images you’re referring to here.

Are you saying that the image being referenced here is located on a different server and accessed through a non-local URL? (And that you’re looking to store that reference url?)

Or are you saying that you’re going to copy the image from the original source to your server?

in my project users can only register and login with social network like google , facebook .
this social network after login give me a link of user profile picture and i dont download and save this picture in local . i save only the url in image field and dont create extera url field .

also user can upload image after login and i save only media url like /media/sample.png

now i need access both url .

but django give me social profile link like this : localhost:8000/media/https://google./user.png

how can access and tell django i just need my url and dont change to media url for local .

If the image is not local - if you’re going to use the image from the url of the external resource, then do not store that in an image field. That reference url should be stored in a UrlField. (You don’t actually have an image.)

Your code then needs to determine which field to use in the template. (You could create a model method to check for a local image and choose the appropriate field to render.)

1 Like

thanks for your help .
i saw my database and image field save my social url correct . like(https://example.com/user.png)
I was looking for a way not to add an extra field to my model and to use one field for two purposes (as I wrote in the code above).
If there is no way, I have to save the images or not use them at aاl.

Add the extra field.

Don’t try to make Django fit a bad design. Fix the code.

1 Like