1
我想出來的Django,衝進下面的問題產生:圖像與錯誤的URL
我有一個具有各種屬性之間是圖像的模型類Property
。該image
屬性定義爲:
image = models.FileField(
upload_to = 'properties',
default = 'properties/house.jpeg')
目錄properties
是在settings.py
定義爲images
子目錄:
MEDIA_ROOT = '/Users/.../Development/pms/images/'
MEDIA_URL = 'http://localhost:8000/images/'
從類似的帖子派生的SO關於這個話題,我添加了下面我Property
型號:
def admin_image(self):
return '<img src="images/%s" width="100"/>' % self.image
admin_image.allow_tags = True
我加入admin_image()
的屬性列表顯示:
list_display = ('admin_image', ...)
當我檢查在管理應用程序中的圖像的URL,我得到如下:爲生成URL
http://127.0.0.1:8000/admin/properties/property/images/properties/house.jpeg/
這會產生一個404不正確。首先,路徑是不正確的,其次是網址末尾有一個尾部/尾部。
我很明顯失去了一些東西......我做錯了什麼?
編輯:
感謝@okm爲各種指針。我做了以下內容:
添加以下到我的urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
... original url patterns ...
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^images/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
然後settings.py中集MEDIA_ROOT:
absolute/filesystem/path/to/images
而且在settings.py集MEDIA_URL:
/images/
謝謝。現在url看起來不錯:http:// localhost:8000/images/properties/house.jpeg但是圖片仍然沒有顯示。我注意到你的第二個鏈接使用一個ImageField作爲我使用FileField的圖像。我讀過ImageFields需要額外的庫來安裝,我沒有做。是否需要使用ImageField在Django中顯示圖像,還是圖像不顯示是由其他內容引起的? – Roger
@Roger ImageField更好地工作w /圖像文件,因爲它會帶來圖像特定的清潔和屬性,如'寬度'和'高度'。因此,如果沒有特殊原因,請繼續使用ImageField作爲圖像文件,而不要使用FileField。對於404問題,您是否配置了devserver以在MEDIA_URL中提供媒體文件?因爲devserver不會自動提供媒體文件,否則是靜態文件。 – okm
@Roger檢查http://stackoverflow.com/a/10408267/165603 – okm