Django Image未找到使用模板标签

时间:2017-11-27 13:16:09

标签: python django

我现在遇到了很多麻烦,所有给出的解决方案对我没有帮助。 如果我使用模板变量{{userprofile.photo.url}}(结果是Alt文本),我想显示的图像配置文件不会出现,但是当我将路径放到图像上时它确实有效:/dashboard/media/dashboard/photo/profils/user.png。

我试图调试,似乎网址很好但结果给出的是:

[27/Nov/2017 13:55:07] "GET /dashboard/ HTTP/1.1" 200 44757
Not Found: /media/dashboard/photos/profils/user.png
[27/Nov/2017 13:55:07] "GET /media/dashboard/photos/profils/user.png HTTP/1.1" 404 2295

这里是项目的文件:

项目结构:

project_dir/
 dash-app/
    __init__.py
    settings.py
    urls.py
    wsgi.py
 dashboard/
    __init__.py
    admin.py
    app.py
    forms.py
    models.py
    urls.py
    views.py
    ...
  templates/
    dashboard/
       index.html
       ...
  static/
    dashboard/
      images/
         logo9.png
         ...
  media/
    dashboard/
      photos/
        profils/
           user.png
           ...

在urls.py上:

from django.conf.urls import url
from dashboard import models
from dashboard import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^$', views.index, name='index'),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

在settings.py上:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "dashboard", "static")

#dashboard/media/
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media", "dashboard")

在models.py上:

from django.core.files.storage import FileSystemStorage

image_storage = FileSystemStorage(
    # Physical file location ROOT
    location='{0}/'.format(settings.MEDIA_ROOT),
    # Url for file
    base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
)

def image_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/dashboard/picture/<filename>
    return 'photos/profils/{0}'.format(filename)

def logo_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/dashboard/picture/<filename>
    return 'photos/logos/{0}'.format(filename)

...

   # Photos
    photo = models.ImageField(blank=True, 
                              upload_to=image_directory_path, 
                              storage=image_storage)

    # Logo de l'activité
    photo = models.ImageField(null=True, 
                              upload_to=logo_directory_path, 
                              storage=image_storage)

在views.py上:

def index(request):
    connected = models.UserProfile.objects.get(user=request.user)
    print(connected.photo.url)
    context={
        'userprofile':connected,
    }    
    return render(request, 'dashboard/index.html', context)

在index.html上:

 <!-- menu profile quick info -->
  <div class="profile clearfix">
    <div class="profile_pic">

    {% if userprofile.photo %}
        <img src="{{ userprofile.photo.url }}" alt="User" class="img-circle profile_img">
    {% else %}
        <img src="media/dashboard/photos/profils/user.png" alt="..." class="img-circle profile_img">
    {% endif %}
    </div>
    <div class="profile_info">
      <span>Bienvenu,</span>
      <h2>{{ userprofile }}</h2>
    </div>
  </div>
  <!-- /menu profile quick info -->

我使用的是python 3和Django 1.11.5 感谢tou的帮助!

  

编辑:我已经在私人导航上打开了应用程序以重新加载并查看缓存中是否有某些内容,并且知道我发现没有任何效果,{{ userprofile.photo.url|slice:"1:" }}media/dashboard/photos/profils/user.png。是否可以重新加载&gt;媒体的文件链接到项目或类似的东西。因为如果手动将图像添加到文件夹中或者如果我通过Django Admin Interface上传它,是否有一些区别?

     

已解决:我改变了这些行:   MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media", "dashboard")MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media")

     

image_storage = FileSystemStorage( # Physical file location ROOT location='{0}/'.format(settings.MEDIA_ROOT), # Url for file base_url='{0}/dashboard/'.format(settings.MEDIA_URL), )

     

     

image_storage = FileSystemStorage( # Physical file location ROOT location='{0}/dashboard/'.format(settings.MEDIA_ROOT), # Url for file base_url='{0}/dashboard/'.format(settings.MEDIA_URL), )

2 个答案:

答案 0 :(得分:0)

在模型上定义一个计算属性,返回媒体文件的相对URL。

class CustomUser(models.Model):
...

   @property
   def photo_url(self):
       return '{}{}'.format(settings.MEDIA_URL, self.img)

然后在模板中使用此计算属性:

{% if userprofile.photo %}
    <img 
       src="{{ userprofile.photo_url }}"
       alt="User" 
       class="img-circle profile_img"
    >
{% else %} 

如果您正在开发中运行,可以register a route in your project urls for media files这样:

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

否则,请考虑将媒体文件上传到Amazon S3或writing server rules to serve your assets等数字资产管理系统。

答案 1 :(得分:0)

已解决:

我更改了这些行: MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media", "dashboard")MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media")

image_storage = FileSystemStorage(
          # Physical file location ROOT
          location='{0}/'.format(settings.MEDIA_ROOT),
          # Url for file
          base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
      )

image_storage = FileSystemStorage(
          # Physical file location ROOT
          location='{0}/dashboard/'.format(settings.MEDIA_ROOT),
          # Url for file
          base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
      )