1

我在 Django 中使用 couchdb-python。我正在寻找一种在模板中显示图像(作为文档附件存储在数据库中)的方法。奇怪的是,我在网上找不到任何关于如何做到这一点的例子。

目前,在 views.py 我有这样的事情:

def displaypage(request,id):
    docs = SERVER['docs']
    try:
        doc = docs[id]
    except ResourceNotFound:
        raise Http404
    ...
    attachments = doc['_attachments']['someimage.jpg']
    ...
    text_marked_down = markdown.markdown(doc['text'])
    return render_to_response('couch_docs/display.html',{'row':doc,'attachments':attachments,'doctext':text_marked_down,...},context_instance=RequestContext(request))

然后,在模板 display.html 中:

{% extends 'site_base.html' %}

{% block wrapper %}
{{ attachments }}
<div>{{ doctext|safe }}</div>
{{ endblock }}

我看到文字很好,但对于图像我只看到以下内容:{u'stub':True, u'length':27018,u'revpos':19,u'content_type': u'image/jpeg '}

所以,很明显我没有传递实际的图像,或者无论如何都没有正确显示它。奇怪的是,我无法在网上找到如何实际执行此操作的示例。谁能给我指一个,或者在这里提供?

4

2 回答 2

2

您正在使用模板引擎来呈现 HTML 文档。该文档将由 Web 浏览器解释,就像任何其他 HTML 文档一样。

想一想 HTML 页面是如何包含图像的。图像永远不会内嵌在 HTML 文档本身中。HTML 页面包含指示浏览器单独加载图像并在适当位置显示的引用。

<img src="/path/to/image" />

因此,同样,您将需要:

于 2011-05-09T18:43:53.900 回答
0

深入了解数据库后,您可能需要考虑构建每个文档附件的 url,如下所示:

def function():

    couch = couchdb.Server()    #connect to server
    db = couch['img']         #connect to database which contains docs with img attachments
    doc_id = []                #create list of id's
    http_docid = []            #create list to populate href for picture path

    for i in db:                #for each id in the db
        doc_id.append(i)       #add to the carid list
        doc = db[i]             #get the document id
        for key in (doc['_attachments']):   #for the key in the doc '_attacments' payload
            print key #just to confirm
        href_docid.append(('http://yourdbDomain/dbname/'+i+'/'+key))  #create a uri and append to a list
    return href_docid     

下面我使用 Jinja2 的模板:

     {% for img in function() %}

      <img class="some-class" src="{{ img }}">

     {% endfor %}

希望这被证明是有用的!

于 2016-05-10T06:48:20.027 回答