我无法从数据库信息中显示我的图像文件。如果我直接输入文件名,它可以正常工作,但代码显示图像已损坏。非图像变量工作正常,图像作为文件名的CharField存储在模型中(我现在意识到这可能不是最好的,但我认为改变可能为时已晚?)我做错了什么?
<div class="product_image" >
{% load static %} <img src="{% static "images/{{p.image.url}}" %}" alt={{p.name}}/>
(我也试过{{p.image}}但没有运气。)
以下是相关设置 - 仍然混淆了媒体与静态。
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'),
)
以下是产品型号(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
答案 0 :(得分:2)
你不能像那样嵌套Django标签。
如果p.image是CharField,请使用
<img src="{% static p.image %}" alt="{{p.name}}"/>
您需要确保在字段中存储正确的路径。
答案 1 :(得分:1)
由于它只是存储在p.image.url
中的文件名,因此可以使用:
<img src="{{ STATIC_URL }}images/{{p.image}}" alt={{p.name}}/>
您的context = RequestContext(request)
视图中必须有{{ STATIC_URL }}
才能正常工作。
您可以阅读RequestContext
here.