我正在学习在 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/')
它只显示图像的边框,而不显示实际图像
在您的templates/index.html中,您要求提供情侣对象的网址 <img class="profile_pic" src="{{ couple.image_bride.url }}"/>
但夫妇没有传递到您的模板。
更改此行context = {'image_bride':image_bride, 'image_groom':image_groom}
对此context = {'couple': obj}
我是一名优秀的程序员,十分优秀!