[Fixed]-Image.url returns local full path in view.py Django 1.6

1πŸ‘

βœ…

I have just tested an example from scratch using Django 1.8.3 and Python 2.7.6, and it worked like a charm:

# models.py:
from django.db import models


class ImageTest(models.Model):
    photo = models.ImageField(upload_to='photos')

# settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'

I set up admin for this model, uploaded an image, and via shell I tested the url field of this image:

>>> from main.models import ImageTest
>>> ImageTest.objects.all()[0].photo.url
'media/photos/zunzun_logo.png'

As you can see it is a relative path. I actually don’t know what can be happening in your case. Perhaps if you can paste some code here I can help you a little bit more ;). Hope this can help you to find a solution.

0πŸ‘

I had this problem as well.
A common reason for getting a full local path is when you use a function to change the path in the upload_to field. You just have to make sure that function returns a relative path, not a full path.
In my case my function would create de necessary dirs if none existed. I needed to use the full MEDIA_ROOT path for that, but had to make sure it returned a relative path value for upload_to.

πŸ‘€Joao Neves

Leave a comment