首页 > 解决方案 > 如何在模板中显示文件 - django

问题描述

我想显示一个上传的文件:

{% for post in posts %}
       <img src="{{post.image.url}}">    
       <h3>{{post.title}}</h3>
       <button type="button" class="btn view-project-btn">view more</button>
       <div class="item-details">
           <div class="description">
                 <p>{{post.description}}</p>
           </div>
           <div class="info">
                <ul>
                    <li>created - <span>{{post.date_creation}}</span></li>
                    <li>le theme de recherche -<span>{{post.sous_titre}}</span></li>
                    {{post.body|safe}}
                   
                    <iframe src="{{post.file.url}}" width="100%" height="500px"></iframe>
                </ul>
              ....                
{% endfor %}

这是我的看法

def home(request):
    posts = Post.objects.filter(active=True)
    context = {'posts':posts}
    return render(request,'base/index.html',context)

但它不起作用它适用于 imagefield {{example.image.url}},这是我模型中的属性file = models.FileField(null=True, blank=True,upload_to="sources")

感谢您的帮助和建议

错误 : 在此处输入图像描述

未找到:/sources/file1.pdf

网址.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('post.urls')),
    path('ckeditor/', include('ckeditor_uploader.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)

在我的设置中

BASE_DIR = Path(__file__).resolve().parent.parent

STATIC_URL = '/static/'
MEDIA_URL = '/media/'


STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static') 
]

MEDIA_ROOT = os.path.join(BASE_DIR,'static/media')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

标签: djangodjango-viewsdjango-templates

解决方案


编辑媒体根

MEDIA_ROOT = os.path.join(BASE_DIR,'static/images')

这是错误的,您不能在静态根目录中拥有媒体根目录

删除 static/ 并重试


推荐阅读