[Answered ]-How to display a couchdb image attachment in a Django template


You are using the template engine to render an HTML document. That document will be interpreted by the web browser just like any other HTML document.

Think about how an HTML page contains an image. The image is never inline within the HTML document itself. The HTML page contains a reference to instruct the browser to separately load the image and display it in place.

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

So, likewise, you will need to:

  • create a separate view that will only return the binary data of the image. Set the mime type appropriately. See http://effbot.org/zone/django-pil.htm for some ideas how to return an image, but in your case set the contents of the response to be your image content.
  • add an <img …> tag to your template that calls the new view you created.


once you drill down your db, you might want to consider building the url of each documents attachment as follows:

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     

And below im using Jinja2’s templating:

     {% for img in function() %}

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

     {% endfor %}

Hope this proves usefull!


Leave a comment