Jor*_*ris 4 html python django model imagefield
我在我的 Django 模型中使用了一个 imageField 并且当我尝试在 html 中显示它时无法识别照片。
这是我的models.py
from django.db import models
class LatestRelease(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=300)
cover = models.ImageField(upload_to='personal/static/img/')
display = models.BooleanField(default=True)
Run Code Online (Sandbox Code Playgroud)
这是view.py
from django.shortcuts import render
from personal.models import LatestRelease
def index(request):
releases = LatestRelease.objects.all()
return render(request, "personal/home.html", {'releases': releases})
Run Code Online (Sandbox Code Playgroud)
HTML代码
{% for release in releases %}
<img src="{{ release.cover.url }}" class='' height='235' width='235'>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
所以基本上,图像路径{{ release.cover.url }}是/personal/static/img/[image name]
,我的照片只有在我使用 url 路径/static/img/[image name]作为源时才会出现。
无论如何要取出/personal从创建的字符串{{ release.cover.url }}?还是为了让我的 img 源接受以下文件/personal/static/img/[image name]?
如果您也显示了 settings.py 和 urls.py 文件,这可能会有所帮助,但我猜您的开发服务器未设置为提供该personal/static/img/[image name]文件。要进行设置,您需要调整 settings.py 和主项目 urls.py 文件。
设置.py:
# Add these
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
Run Code Online (Sandbox Code Playgroud)
MEDIA_ROOT指示当您MEDIA_URL点击时可以从哪里提供文件(例如当您的浏览器要求该图片时)。为了实际提供您需要设置视图的文件,有一个内置的帮助函数用于在开发中提供这些文件,将其添加到您的主项目 urls.py 文件中
网址.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# your other views
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Run Code Online (Sandbox Code Playgroud)
然后你应该再次上传图片,它会被保存在media/<upload_to>/<picturename>,在你的情况下media/personal/static/img/<picture_name>。您的服务器现在实际上知道在哪里可以找到它。
查看 文档以获得更好的示例。
您使用的硬编码 url 有效,/static/img/[image name]因为 Django 开发服务器默认可以从static/项目根目录中的目录以及static/应用程序根目录中的任何文件夹提供静态文件。因此,您在upload_toImageField 中的争论创建了该/personal/static/文件夹,这是一种幸运的巧合。然后因为DEBUG = True在 settings.py 中设置了你被设置为自动提供它。这在上面的链接文档中有描述(更好)。
| 归档时间: |
|
| 查看次数: |
1312 次 |
| 最近记录: |