2012-01-13 35 views
13

我已經得到了下面的模型在我的Django應用程序:如何在模板中獲取ImageField URL?

class Image(models.Model): 
    image = models.ImageField(
     upload_to='images/', 
     height_field='height', 
     width_field='width' 
    ) 
    credit = models.CharField(max_length=50, blank=True) 
    caption = models.TextField(blank=True) 
    article = models.ForeignKey(Article) 
    width = models.PositiveIntegerField(
     blank = True, null = True, 
     editable = False, 
     default = 0 
    ) 
    height = models.PositiveIntegerField(
     blank = True, null = True, 
     editable = False, 
     default = 0 
    ) 

我已經設置了MEDIA_ROOT到一個名爲/ hmedia /在我的Apache網站根目錄下,我已經設置MEDIA_URL到'http://localhost/hmedia/'。這似乎奏效了 - 我已經通過Django管理站點成功上傳了幾張圖片,並且我可以通過http://localhost/hmedia/images/[filename]查看這些圖片。 Django管理站點實際上顯示了我的文件名,並鏈接到每個圖像的實時URL,並且鏈接工作。

我的問題是,我不能工作了如何獲得這些圖片的網址或文件名在我的模板:

<ul> 
{% for image in article.image_set.all %} 
    <li>Caption: "{{image.caption}}", Credit: "{{image.credit}}", URL: "{{image.url}}"</li> 
{% endfor %} 
</ul> 

上面的模板結果的輸出:

<ul> 

    <li>Caption: "here's an image caption", Credit: "some photographer", URL: ""</li> 

    <li>Caption: "Another caption here", Credit: "Another photographer", URL: ""</li> 

</ul> 

換句話說,它可以正確輸出每個圖像的標題和信用屬性,但它不會爲{{image.url}}輸出任何內容。

如何在我的模板中獲取圖片的網址? Django管理界面模板如何做到這一點? (我在管理模板目錄紮根左右,但無法找到我要找的。)

+2

你只需要訪問像場本身。路徑和的.url - 所以'image.image.path', 'image.image.url'。原因是,您試圖訪問模型實例上的那些不存在的屬性。 – AdamKG 2012-01-13 12:26:41

回答

30

你需要{{ image.image.url }} & {{ image.image.path }},而{{ image }} - 只是一個Image對象

1

你的代碼改成這樣:

<ul> 
{% for image in article.image_set.all %} 
    <li>Caption: "{{ image.caption }}", Credit: "{{ image.credit }}", URL: "<a href ='/{{ image.image }}'{{ image.image }}</a>"</li> 
{% endfor %} 
</ul> 

更改{{image.url}}到{{image.image}}因爲 '圖像配' 包含圖像的位置。你沒有從'.url'獲得任何價值的原因是你的模型中沒有你的類Image中的字段url。

-6

創建一個文件夾「靜態」,在你的Django項目,將它添加到你的設置文件

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'), 
) 

如果沒有這條線在你的設置文件還添加它

BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 

現在在模板中可以使用

{% static image.image.url %} 
+2

這將無法正常工作,因爲圖像字段字段與靜態文件無關! – azuax 2015-04-04 00:04:48