我无法从数据库信息中显示图像文件。如果我直接键入文件名,它可以正常工作,但代码如同显示一个破碎的图像。非图像变量工作正常,并且图像作为文件名的CharField存储在模型中(我现在认识到这可能不是最好的,但我认为改变可能为时过晚?)我在做什么错误?无法显示Django图像
<div class="product_image" >
{% load static %} <img src="{% static "images/{{p.image.url}}" %}" alt={{p.name}}/>
(我也尝试{{p.image}},没有运气。)
这里是相关设置 - 仍然困惑Media对比静态的。
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
我已经肯定来过这里和Django开始出来的时候了。你为什么使用CharField来存储图像?它是完整的还是相对的路径或URL? – woemler
我不知道为什么我这样做,除了我还在学习。当我查看加载后的页面源时,我得到:
这让我感到惊讶;我原以为我会得到一个完整的路径。尽管如此,其他地方的一个类似的静态图像 - 我输入文件的名称而不是使用变量 - 运行良好。它与字符串内部的变量有什么关系,所以它不会被渲染?我试图把它放在引号外,但它引发了一个SyntaxError。 –
thumbtackthief
如果您使用[south](http://south.readthedocs.org/en/0.7.6/tutorial/part1.html),则可以编写自定义迁移以将char字段转换为[ImageField](https ://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield) – Nathaniel