2014-03-24 144 views
1

目前正在開發一個小型的Django電子商務項目,並遇到一個小問題。作爲參考,我使用免費在線提供的Django書籍Tango。Django - 圖像顯示不正確

我在我的模型中設置了一個ImageField,以便爲Product的模型指定產品的圖像。我還有一個名爲Category的模型,它使用ForeignKey引用到產品模型。

圖像上傳到模型中的/ static/products_img文件夾,但是當圖像顯示在我的模板中時,圖像鏈接到/ static/static/products_img文件夾。但是,當我刪除模型中的/靜態圖像,然後通過管理界面上傳圖像時,會將其上載到/ products_img而不是靜態文件夾,當然它顯示正常。但是......它變得更加怪異,當我刪除新創建的目錄並將圖像放置在靜態文件夾中的/ product_img文件夾中時,它仍然顯示!

我很困惑。

models.py 

class Product(models.Model): 
... 
    image = models.ImageField(upload_to='static/products_img', blank=True) 


template.html 
<a href="{{ product.slug }}"><img src="{{ STATIC_URL }}{{ product.image }}" alt="{{ product.name }}" /></a> 


settings.py 
... 
SETTINGS_DIR = os.path.dirname(__file__) 
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir) 
PROJECT_PATH = os.path.abspath(PROJECT_PATH) 
... 
STATIC_PATH = os.path.join(PROJECT_PATH,'static') 
STATIC_URL = '/static/' 
STATICFILES_DIRS = (
    STATIC_PATH, 
) 

回答

1

我認爲你有靜態和媒體文件之間的混淆。靜態文件與您的應用程序(CSS,JS ...)捆綁在一起,而用戶上傳媒體文件。

據我所知,你的產品圖像是媒體文件,而不是靜態文件。

如果你更換模板部分:

<a href="{{ product.slug }}"><img src="{{ product.image.url }}" alt="{{ product.name }}" /></a> 

和你的模型:

image = models.ImageField(upload_to='products/img', blank=True) 

並添加相應的設置到您的settings.py:

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) 
# with this, your media directory will be the same directory than your settings.py file 
# you can also use a standard path like "/var/www/media" 
# IMPORTANT : In any case, you have to create the directory by hand 
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media") 
MEDIA_URL = "/media/" 

如果您將圖片上傳到產品中,則現在應將其保存在MEDIA_ROOT導演年。模板中顯示的網址應爲/media/projects/img/image_name

+0

映射似乎與您發佈的內容一起工作,但是,替換模板部分會產生此錯誤:''圖像'屬性沒有與之關聯的文件。'我嘗試搜索此錯誤但無濟於事。 – user2942863

+0

對它進行排序,必須在模板中添加「{{MEDIA_URL}}」。謝謝!似乎我在壓力中忽略了一些東西。 – user2942863