I’m having trouble getting my image files to appear from the database info. If I type the filename directly, it works fine, but the code as it is shows a broken image. The non-image variables work fine, and the image is stored in the model as a CharField of the filename (which I realize now may not have been best, but I think it may be too late to change?) What am I doing wrong?
<div class="product_image" >
{% load static %} <img src="{% static "images/{{p.image.url}}" %}" alt={{p.name}}/>
(I’ve also tried {{p.image}} with no luck.)
Here are the relevant settings–still confused about media vs static.
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'staticcoll')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), 'static'),
)
Here is the Product model (p):
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
price = models.DecimalField(max_digits=9,decimal_places=2)
old_price = models.DecimalField(max_digits=9,decimal_places=2,
blank=True,default=0.00)
image = models.CharField(max_length=50, default="imagenotfound.jpeg")
is_active = models.BooleanField(default=True)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField(Category)
store_name = models.ForeignKey(Store, blank = True, null = True)
class Meta:
db_table = 'products'
ordering = ['-created_at']
def __unicode__(self):
return self.name
Since it’s just the file name stored in
p.image.url, this will work:<img src="{{ STATIC_URL }}images/{{p.image}}" alt={{p.name}}/>You must have
context = RequestContext(request)in your view for{{ STATIC_URL }}to work.You can read about
RequestContexthere.