我已经设置了一个活动的Django模型,其中包含以下字段:
class Activity(models.Model):
...
thumbnail = models.ImageField(upload_to="thumbs/", blank=True, null=True)
通过管理界面,我可以将正确放置的图像上传到主目录的thumb文件夹中。当我尝试编辑我创建的活动时,界面显示:Currently: thumbs/image.png
这是一个指向http://localhost:8000/media/thumbs/image.png
的超链接。当我单击此链接时,我收到404页面找不到错误。如何才能获得指向我上传的图像的链接?如果可能,如何直接在管理界面中显示图像?
编辑:
MEDIA_ROOT = '/Users/.../mysite/media/'
;
MEDIA_URL = 'http://localhost:8000/media/'
;
urls.py的内容:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
谢谢!
答案 0 :(得分:9)
<强> settings.py 强>
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
models.py
class Activity(models.Model):
...
thumbnail = models.ImageField(upload_to="thumbs/", blank=True, null=True)
def image_(self):
return '<a href="/media/{0}"><img src="/media/{0}"></a>'.format(self.thumbnail)
image_.allow_tags = True
class AdminName(admin.ModelAdmin):
.........
list_display = ('image_',)