2017-05-29 72 views
1

絕對Linux的路徑,我有以下型號的Django ImageField的顯示模板

class Product(SiteBaseFields): 
    name = models.CharField(max_length=500) 
    description = models.CharField(max_length=500) 
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0.00) 
    unit = models.CharField(max_length=500, null=True, blank=True, default=0.00) 
    image = models.ImageField(upload_to=settings.MEDIA_ROOT, null=True, blank=True) 

    def __unicode__(self): 
     return self.name 

在數據庫中的產品記錄是

d762ugo5f5706v=> select id, image from dj_commerce_product 
d762ugo5f5706v-> ; 
id |            image 
----+------------------------------------------------------------------------------------------------------ 
17 | /var/www/dj_node_project/media/iphone_4TTsU22.jpg 
19 | /var/www/dj_node_project/media/samsung_phone_5VlDULp.png 
18 | /var/www/dj_node_project/media/201409-w-americas-best-coffee-cities-new-orleans-cafe-du-_CTcGKwx.jpg 
(3 rows) 

當我在模板做<img src="{{MEDIA_URL}}{{product.image.url}}" />,我回去<img src="/var/www/dj_node_project/media/iphone_4TTsU22.jpg">,並且圖像的URL是完全錯誤的。我找不到原因。

+1

可以顯示的設置文件,你聲明什麼的MEDIA_URL和MEDIA_ROOT在你的settings.py媒體路徑 – Exprator

+0

? – rrmerugu

回答

1

更改MEDIA_URL和MEDIA_ROOT在你的settings.py。

# settings.py 
MEDIA_URL = 'media/' 
MEDIA_ROOT = os.path.join(BASE_DIR , "media") # this is the root/absolute path for uploaded files 

重新上傳一些東西,檢查是否能正常工作。該問題與MEDIA_URL或MEDIA_ROOT有關。它是一個常見的初學者錯誤配置媒體設置錯誤。

僅供參考:

https://docs.djangoproject.com/en/1.11/ref/settings/#media-root https://docs.djangoproject.com/en/1.11/ref/settings/#media-url

編輯:

FileField.upload_to此屬性提供設置 上傳目錄和文件名的方式,並能有兩種方式。在這兩種情況下 ,該值被傳遞給Storage.save()方法。

如果指定一個字符串值,它可能包含strftime()格式, 將被文件上傳的日期/時間替換(因此 上傳的文件不會填滿給定的目錄)。例如:

class MyModel(models.Model): 
    # file will be uploaded to MEDIA_ROOT/uploads 
    upload = models.ImageField(upload_to='uploads/') 
    # or... 
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30 
    upload = models.FileField(upload_to='uploads/%Y/%m/%d/') 
+0

這是我已經! – user1187968

+0

你可以刪除這個'upload_to = settings.MEDIA_ROOT'部分嗎?並看看它是如何工作的?因爲我沒有看到你應該這樣做的任何好理由。只要把它'upload_to ='some_folder''。 – rrmerugu

+0

沒有編輯固定的問題? – rrmerugu