简体   繁体   中英

Django, display image in template that is uploaded from admin panel

i'm learning to upload and display images in Django but I've run into a block where I can't figure out how to call the images location from the database and then display it in a template, i've uploaded image from admin panel and wants to display it in template...

models.py from django.db import models from time import time

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/')

it shows only borders of the image but not actual image 在此处输入图片说明

In your templates/index.html , you asking for url on couple object <img class="profile_pic" src="{{ couple.image_bride.url }}"/> but couple is not passed to your template.

Change this line context = {'image_bride':image_bride, 'image_groom':image_groom}
to this context = {'couple': obj}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM