-1

我无法从数据库信息中显示我的图像文件。如果我直接输入文件名,它可以正常工作,但代码显示损坏的图像。非图像变量工作正常,图像作为文件名的 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
4

2 回答 2

2

你不能像这样嵌套 Django 标签。

如果 p.image 是 CharField,请使用

<img src="{% static p.image %}" alt="{{p.name}}"/>

您需要确保字段中存储了正确的路径。

于 2013-01-24T18:07:51.463 回答
1

由于它只是存储在 中的文件名p.image.url,这将起作用:

<img src="{{ STATIC_URL }}images/{{p.image}}" alt={{p.name}}/>

你必须有context = RequestContext(request)你的看法{{ STATIC_URL }}才能工作。

你可以在RequestContext 这里阅读。

于 2013-01-24T18:11:27.490 回答