在我的Django PhotoViewer应用程序的models.py中,我为Photo类定义了一个imageField,以在网站上显示图像。我已经通过Django管理页面上传了一些照片,但都没有显示。我确实看到所有这些照片都在我的/ static / images文件夹中本地上传。但是,当我转到我的照片索引(照片页面列表):127.0.0.1:8000:photoViewer/photos
时,我会看到以下页面:
models.py
:
from django.db import models
#photoViewer/: (index) photostream (list all photos)
class Photo (models.Model):
photo_title = models.CharField(max_length=200)
#how to retrieve from metadata of file?
date_taken = models.DateField('date taken', default=None, blank=True, null=True)
photo_img = models.ImageField(upload_to = "images/", default= "")
def __str__(self): # __unicode__ on Python 2
return self.photo_title
photoViewer / urls.py
from django.conf.urls import patterns, url
from photoViewer import views
urlpatterns = patterns('',
# "photoViewer/photos"
url(r'^photos/$', views.IndexView.as_view(), name='index'),
# "photoViewer/photos/5/"
url(r'^photos/(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
# "photoViewer/albums/"
# Display list of albums
url(r'^albums/$', views.AlbumsIndexView.as_view(), name='albumsIndex'),
# "photoViewer/albums/1"
# Display photos for a given album
url(r'^albums/(?P<pk>\d+)/$', views.AlbumDetailView.as_view(), name='albumDetail'),
url(r'^test/$', views.TemplateTestView.as_view(), name='templateTest'),
)
photoViewer / views.py
from django.shortcuts import get_object_or_404, render
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from photoViewer.models import Photo, Album
from django.core.urlresolvers import reverse
from django.views import generic
# Create your views here.
class TemplateTestView (generic.ListView):
model = Photo
template_name = 'photoViewer/test.html'
class IndexView(generic.ListView):
#By default: Uses <app name>/<model name>_detail.html
#as template
template_name = 'photoViewer/photo_index.html'
context_object_name = 'latest_photo_list'
def get_queryset(self):
return Photo.objects.order_by('-date_taken')[:5]
class DetailView(generic.DetailView):
model = Photo
#By default: Uses <app name>/<model name>_detail.html
#Unless specified by template_name
template_name = 'photoViewer/photo_detail.html'
#context_object_name = <new name>
class AlbumsIndexView(generic.ListView):
template_name = 'photoViewer/albums_index.html'
context_object_name = 'latest_albums_list'
def get_queryset(self):
return Album.objects.order_by('-date_created')[:5]
class AlbumDetailView(generic.DetailView):
model = Album
template_name = 'photoViewer/albums_detail.html'
photoViewer/templates/photoViewer/photo_detail.html
(照片详情页面模板):
<h1>Photo Detail</h1>
<li>{{ photo.photo_title }}</li>
<li>{{ photo.date_taken }}</li>
<img src="/static/{{ photo.photo_img }}" alt={{ photo.photo_title }}>
<h2>Albums Association</h2>
{% if photo.album_set.all %}
<ul>
{% for album in photo.album_set.all %}
<li>{{ album.album_title }}</li>
<!-- <li><a href="{% url 'photoViewer:detail' photo.id %}">{{ photo.photo_title }}</a> {{ photo.date_taken }} </li>
-->
{% endfor %}
</ul>
{% else %}
<p>This Photo is Not in Any Album</p>
{% endif %}
我安装了最新版本的pillow
答案 0 :(得分:5)
每当您使用模型对象显示图像时,您需要使用object.photo_img.url
来访问图像路径。但在此之前,请确保photo_img不包含emptry string。
[EDITED] 除非您在Django文档中提到的urls.py条目中添加静态URL,否则您的开发服务器将不会提供图像
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT)
参考:https://docs.djangoproject.com/en/1.7/howto/static-files/#serving-static-files-during-development
答案 1 :(得分:2)
我总是像这样配置我的开发环境:
Django - 用于处理请求,nginx - 用于提供静态和媒体。
另外,我建议您为开发网站设置域名。
您需要像这样设置STATIC_ROOT和MEDIA_ROOT:
# settings.py
import os
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
MEDIA_ROOT = os.path.join(SITE_ROOT, 'static')
注意:不要将静态文件放入STATIC_ROOT!在每个应用程序中创建静态文件夹,然后使用collectstatic命令。它将遍历所有已安装的应用程序并将其中的所有静态复制到STATIC_ROOT。但是在添加或编辑某些文件后需要运行此命令。如果你想经常编辑它们(对于js和css文件),只需对collectstatic命令使用“-l”选项 - 它将创建链接而不是副本。
你应该这样做吗? - 默认的django开发服务器一次只能处理一个请求。例如:如果页面上有10个文件,并且一个文件请求时间是200毫秒,那么加载页面大约需要2000毫秒。 Nginx可以根据需要一次处理多个请求 - 总页面加载时间约为200毫秒。当你甚至无法在页面重新加载时闪烁时,它真的很棒。另一个好处 - 你不会在django请求日志中看到任何无用的请求。使用上面显示的设置,django会自动将文件上传到MEDIA_ROOT。
Nginx安装很简单:sudo apt-get install nginx
示例nginx配置:
server {
listen 80;
server_name myserver.com; #you can set any domain name you like in /etc/hosts
#just add line 127.0.0.1 myserver.com into it
access_log /var/logs/nginx/myserver.log;
error_log /var/logs/nginx/myserver.log;
location / {
proxy_pass http://127.0.0.1;
}
location /static {
autoindex off;
alias /var/www/myserver/static/; # put here path to you static root
if ($query_string) {
expires max;
}
}
location /media {
alias /var/www/myserver/media/; # put here path to you media root
# if asset versioning is used
if ($query_string) {
expires max;
}
}
if ($host ~* www\.(.*)) {
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1 permanent;
}
}
将nginx配置放入:/ etc / nginx / sites-enabled / you_file_name 之后不要忘记重新加载nginx配置 sudo nginx -t #check配置 sudo服务nginx重新加载 sudo service ngixn restart
如果您无法在页面上看到图片:
我希望我的小建议可以帮助你在硬开发人员的现场直播。 ; - )
答案 2 :(得分:2)
在模板中使用{{STATIC_URL}}而不是硬编码“/ static /".
设置STATIC_ROOT以在开发和服务器环境中正确提供静态文件。
答案 3 :(得分:2)
尝试此操作并在SETTINGS.py中进行更改
STATIC_URL = '/static/'
MEDIA_ROOT = '/home/subhanshu/mysite/static/' #put the absolute path
MEDIA_URL = '/home/subhanshu/mysite/static/' #put the absolute path
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
并对模板进行更改,如下所示:
{% for CLASSNAME in Object %}
<img src="/static/{{CLASSNAME.CLASS_OBJECT}}" />
{% endfor %}
如果您要显示某些静态图片,可以使用此功能:
<img src="{% static 'img/example.jpg' %}">
答案 4 :(得分:1)
首先,您应该注意静态和媒体文件是两回事。静态文件与应用程序一起部署,用于静态内容(css,js,用于样式化站点的图像)。媒体文件上传用于模型等。
接下来的事情:默认情况下,django开发服务器不提供媒体文件。所以你应该让它为他们服务。
要显示图像,您应该使用以下模板代码:
<img src="{{ photo.photo_img.url }}" alt={{ photo.photo_title }}>
您不必(也不应该)自己为静态或媒体文件添加前缀,django将根据您设置中的STATIC_URL
和MEDIA_URL
来处理它。