2015-03-31 102 views
2

我有一個django應用程序,允許用戶使用它提交圖像。現在我的模型看起來像在Django中顯示圖像

class Posting(models.Model): 
    title = models.CharField(max_length=150) 
    images = models.ForeignKey(Image, null=True) 

class Image(models.Model): 
    img = models.ImageField(upload_to="photos/",null=True, blank=True) 

而我試圖在我的模板中顯示圖像,但我似乎無法得到它的工作。我已經去了無數堆棧溢出帖子,並沒有任何運氣。在我的模板中,我有

{ for post in postings } 
    <img src"{{ post.image.url }} #and many variations of this 

但是其他似乎顯示的網址。該網址似乎總是空白。任何幫助將不勝感激!

+0

試試這個 - 因爲你發佈模型有 '圖像' 命名的圖像模型的屬性。 – ancho 2015-03-31 05:19:25

+0

''試試這個。我想問題是相對路徑。追加'/'到路徑。 – 2015-03-31 05:30:43

回答

6

這是我如何得到它的工作。

settings.py

import os 
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 
STATIC_URL = '/static/' 

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

MEDIA_ROOT = (
BASE_DIR 
) 


MEDIA_URL = '/media/' 

models.py ...

image = models.ImageField(upload_to='img') 

urls.py(項目)

if settings.DEBUG: 
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

模板檔案(.html)

<img src="{{ post.image.url }}" alt="img" class="img-responsive img-rounded"> 
1

你應該想到一個類似於:

{% for post in postings %} 
    <img src="{{ post.image.url }}"> 
{% endfor %} 

有幾個需要注意的地方在這裏 -

  • 圖像會擔任一個文件,無論是服務於您的應用程序(的runserver,nginx的, apache等)需要有能力路由該文件。
  • 您必須確保您正在構建模板引擎使用的上下文。它會默默無法在上下文中找不到的值。
+0

謝謝,我試過,但沒有運氣。如果每個帖子都有一個「foreignKey」,這仍然有效嗎?這是一對多正確的? – bencunningham 2015-03-31 04:17:30

1

模板標籤應該是:

<img src="{{ post.images.img.url }}" ... > 
2

做這樣的事情。此代碼正在我的應用程序中工作。

views.py:

def list(request): 
    images = Image.objects.all() 
    return render(request, "list.html", {'images': images}) 

list.html:

{% for i in images %} 
    <img src="{{ i.image.url }}" width="500px"/> 
{% endfor %}