Django图片显示不出来,提示 The requested URL was not found on this server

1、Django图片显示不出来,路径是对的,服务器提示 1The requested URL was not found on this server

下面是相关代码和截图:

settings.py


STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/upload/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload').replace("\\", "/")

urls.py

# -*- coding: utf-8 -*-

from django.conf.urls.static import static
from django.conf.urls import url 
from django.conf import settings


from . import views

app_name = 'yanji'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^actor/$', views.ActorView.as_view(), name='actor_list'),
    url(r'^yanji/(?P<pk>[0-9]+)/$', views.YanjiDetailView.as_view(), name='detail'),
...

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


models.py

@python_2_unicode_compatible
class Actor(models.Model):
    name = models.CharField(verbose_name='演员', max_length=100)
    touxiang = models.ImageField(verbose_name='头像', upload_to='yanyuan_tx/', null=True, blank=True)
    ctime = models.DateTimeField(verbose_name='添加时间', null=True, default=timezone.now)
    ptitle = models.ForeignKey(Ptitle, blank=True)

templates/index.html

          {% for actor in actor_list %}            
            <a class="thumbnail" href="{% url 'yanji:actor' actor.pk %}">
                <div class="swiper-slide">
                      <img src="/upload/{{ actor.touxiang }}" alt="{{ actor.name }}"/>
                      <!-- <br> -->
                      <p>{{ actor.name }}</p>
                    </div>
                </a>            
          {% empty %}
                    <div class="no-actor">暂时无数据</div>
          {% endfor %} 

nginx配置:actorgogo.com

server {
    charset utf-8;
    listen 80;
    server_name actorgogo.com;

    location /static {
        alias /home/zxd/sites/actorgogo.com/actorgogo/static;
    }

    location / {
        proxy_set_header Host $host;


server {
        proxy_pass http://unix:/tmp/actorgogo.com.socket;
    }
}

在本地测试都可以,部署到服务器就图片显示不出来,css、js都正常。

图片路径在新标签打开是这个:

Not Found

The requested URL /upload/yanyuan_tx/2fb5455474997031fed4fc3798c81475.jpg was not found on this server.

不知道是什么原因?

阅读 13.9k
2 个回答

初步判断是URL的问题,不妨尝试下这些写静态路径:

STATIC_ROOT = os.path.join(os.path.dirname(__file__),'static')
STATICFILES_DIRS = [
( os.path.join(BASE_DIR, "static")),
('images',os.path.join(STATIC_ROOT,'img').replace('\\','/')),
('upload',os.path.join(STATIC_ROOT,'upload').replace('\\','/')),
]

可以把upload移入static目录下,方便管理。

DEBUG=False 下,要python manage.py collectstatic

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题