Dan Ward Follow me on Twitter View my LinkedIn profile Subscribe to my news feed   

A self-confessed geek and web developer

 

Blog: Outputting an '_id' value from MongoDB in a Django template

From time-to-time, I'll have a brainwave while trying to figure out something tech-oriented; well, either that or I just want to get something off my chest. Anyhow, if I get round to typing it up, it'll wind up here in the blog.

Created by dan on Friday 15th January, 2010 at 5:48 PM
Tags: Django, MongoDB, Python, Web development

If you've not already noticed, Django's template rendering engine forbids referencing variables, which are prefixed with an underscore. Because of this, we have to faff about with a filter or alike. The below filter should do the job for the _id field. I'm not going in to any more detail on implementing the filter in a project, but it's straightforward enough and well-documented.

Usage:

 

{{ <dict containing _id field>|pk }}

 

Template filter:

 

def pk(value):
   
    # Retrieve _id value
    if type(value) == type({}):
        if value.has_key('_id'):
            value = value['_id']
   
    # Return value
    return unicode(value)