0

I have created model - Profile - which presents user's profile. I have one field which is models.ImageFiled and I have method to get absolute url to this image. I have server in development role, so I've exposed /media folder. When I use full server URL it works. Is there any method to avoid put static web server address?

# Profile 
class Profile(models.Model):

    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    date_of_birth = models.DateField(blank=True, null=True)
    photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True)

    def __str__(self):
        return 'Profile for user {}'.format(self.user.username)

    @property
    def get_absolute_image_url(self):
        return "http://127.0.0.1:8000/{0}".format(self.photo.url)

in settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
zizu1985
  • 1
  • 1

2 Answers2

0

You need an absolute path with a leading slash:

MEDIA_URL = '/media/'
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

After some digging I found the solution. It based on two things:

1) Media url has to be inside static directory to available to display. 2) Uploaded media has to be inside static directory.

My settings.py looks like below:

STATIC_URL = '/static/'
MEDIA_URL = '/static/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "shop", "static", "media")

A help came from here [a link] Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT

zizu1985
  • 1
  • 1