2011-05-09 118 views
1

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

目前,在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'我没有传递实际的图像,或没有无论如何显示它正确。奇怪的是,我无法在网上找到如何实际执行此操作的示例。任何人都可以指给我一个,或者在这里提供吗?

回答

2

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

想想HTML页面如何包含图像。该图像从不在HTML文档本身内联。 HTML页面包含一个引导,指示浏览器单独加载图像并将其显示到位。

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

所以,同样地,你将需要:

  • 创建一个独立的观点,只会返回图像的二进制数据。适当地设置MIME类型。请参阅http://effbot.org/zone/django-pil.htm了解如何返回图片的一些想法,但在您的情况下,请将响应的内容设置为图片内容。
  • 将一个< img ... >标记添加到您的模板,调用您创建的新视图。
+0

好的,很清楚,我知道只是把“{{attachments}}”放在那里是行不通的,我的意思是我拥有一个真正的附件,所以附加图片的有效性/存在性是不是问题。我不知道的是如何显示它,即如何编写视图。我会考虑PIL。 – rossdavidh 2011-05-10 16:45:09

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  

及以下IM使用的Jinja2的模板:

 {% for img in function() %} 

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

    {% endfor %} 

希望这证明有用!

相关问题