django - 如何在模板中显示文件 - 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')
解决方案
编辑媒体根
MEDIA_ROOT = os.path.join(BASE_DIR,'static/images')
这是错误的,您不能在静态根目录中拥有媒体根目录
删除 static/ 并重试
推荐阅读
- python - tkinter 中的 GUI 问题,变量未执行
- reactjs - React 应用程序无法访问 root 的 env 文件
- google-analytics - 标签助手显示重复的 GTM 标签
- php - 如何在 foreach 循环中进行调节
- gis - 无法通过 MS4W 启动 MapServer
- android - 适用于 AWS cognito 用户池的 Android 开发工具包
- reactjs - net::ERR_CONNECTION_REFUSED 在 AWS ECS 负载均衡器中
- javascript - 如何使用nodejs中的mongoose将数组对象的ObjectId作为对同一Mongo Collection中其他数组的引用?
- c++ - 无法在 MSys2 上通过 cmake 编译项目
- laravel - 一般错误:1824 无法打开引用的表