Django,在模板中显示上传的图片网址

时间:2014-03-25 23:33:18

标签: python django

我目前正在学习如何在Django中上传和显示图片,但我遇到了一个块,我无法弄清楚如何从数据库调用图像位置然后显示它在模板中...我缺少什么?

设置

MEDIA_ROOT = '/Users/chr/Desktop/DJANGO-APP/media/'
MEDIA_URL = '/media/'

模型

class Product(models.Model):
    product_name = models.CharField(max_length=200)
    product_description = models.TextField()
    def __unicode__(self):
        return self.product_name

class Image(models.Model):
    product_image = models.ForeignKey(Product)
    image = models.ImageField(upload_to='image')

视图

def productpage(request, product_image_id):
    product = get_object_or_404(Product, pk=product_image_id)
    render(request, 'polls/productpage.html', {'product': product})

HTML

<h1>{{ product.product_name }}</h1>
<br>
{{ product.product_description  }}
<br>
{{ product.image.url }}

编辑:

urls.py(主要)

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

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

1 个答案:

答案 0 :(得分:2)

def productpage(request, product_image_id):
    product = get_object_or_404(Image, product_image=product_image_id)
    render(request, 'polls/productpage.html', {'product': product})

我猜product_image_id是指产品ID?