gpt4 book ai didi

python - Django,在从管理面板上传的模板中显示图像

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:25 27 4
gpt4 key购买 nike

我正在学习在 Django 中上传和显示图像,但我遇到了一个 block ,我无法弄清楚如何从数据库中调用图像位置,然后将其显示在模板中,我已经上传了来自管理面板的图像并希望将其显示在模板中...

models.py从 django.db 导入模型从导入时间开始

class Couple(models.Model):
image_bride = models.ImageField(upload_to='vivaah/static/media')
image_groom = models.ImageField(upload_to='vivaah/static/media')

vivaah/views.py

def index(request, bride_first_name, groom_first_name):
obj = Couple.objects.get(bride_first_name__iexact=bride_first_name)
image_bride = obj.image_bride
image_groom = obj.image_groom
context = {'image_bride':image_bride, 'image_groom':image_groom}
return render(request, 'vivah/index.html', context)

templates/index.html

<img class="profile_pic" src="{{ image_bride.url }}"/>

vivaah/urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from . import views
import os

urlpatterns = [
url(r'^(?P<bride_first_name>[a-zA-Z]+)weds(?P<groom_first_name>[a-zA-Z]+)/$', views.index, name='index'),
]

urls.py

from django.conf.urls import include, url
from django.contrib import admin


from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
import os


urlpatterns = [
url(r'^vivah/', include('vivaah.urls')),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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

它只显示图像的边框,而不显示实际图像 enter image description here

最佳答案

在您的templates/index.html中,您要求提供情侣对象的网址 <img class="profile_pic" src="{{ couple.image_bride.url }}"/>夫妇没有传递到您的模板。

更改此行context = {'image_bride':image_bride, 'image_groom':image_groom}
对此context = {'couple': obj}

关于python - Django,在从管理面板上传的模板中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31787124/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com