user1187968
user1187968

Reputation: 7986

Django ImageField showing absolute Linux path in template

I have the following model

class Product(SiteBaseFields):
    name = models.CharField(max_length=500)
    description = models.CharField(max_length=500)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0.00)
    unit = models.CharField(max_length=500, null=True, blank=True, default=0.00)
    image = models.ImageField(upload_to=settings.MEDIA_ROOT, null=True, blank=True)

    def __unicode__(self):
        return self.name

The product record in the database are

d762ugo5f5706v=> select id, image from dj_commerce_product
d762ugo5f5706v-> ;
 id |                                                image
----+------------------------------------------------------------------------------------------------------
 17 | /var/www/dj_node_project/media/iphone_4TTsU22.jpg
 19 | /var/www/dj_node_project/media/samsung_phone_5VlDULp.png
 18 | /var/www/dj_node_project/media/201409-w-americas-best-coffee-cities-new-orleans-cafe-du-_CTcGKwx.jpg
(3 rows)

When I do <img src="{{MEDIA_URL}}{{product.image.url}}" /> in the template, I get back <img src="/var/www/dj_node_project/media/iphone_4TTsU22.jpg">, and the URL to the image is totally wrong. I can't not find out the cause.

Upvotes: 1

Views: 252

Answers (1)

rrmerugu
rrmerugu

Reputation: 1896

Change the MEDIA_URL and MEDIA_ROOT in your settings.py.

# settings.py 
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR , "media") # this is the root/absolute path for uploaded files

Reupload something and check if this works fine. The issue has be related to MEDIA_URL OR MEDIA_ROOT. Its a common beginners mistake to configure MEDIA settings wrong.

For Reference:

https://docs.djangoproject.com/en/1.11/ref/settings/#media-root https://docs.djangoproject.com/en/1.11/ref/settings/#media-url

Edit:

FileField.upload_to This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method.

If you specify a string value, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example:

class MyModel(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    upload = models.ImageField(upload_to='uploads/')
    # or...
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    upload = models.FileField(upload_to='uploads/%Y/%m/%d/')

Upvotes: 1

Related Questions