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

时间:2015-08-03 12:19:52

标签: python django image django-views

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

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)

模板/ 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,&#39; static / media /&#39;)

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

1 个答案:

答案 0 :(得分:1)

templates / index.html 中,您要求 couple 对象上的网址 <img class="profile_pic" src="{{ couple.image_bride.url }}"/> couple 未传递到您的模板。

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