MongoDB ID’s and Django templates

So. Ran into a little frustration using MongoDB with Django; if you try to represent the _id field of a mongo object using something like {{ mongo_object._id }} or {{ mongo_object.id }}, you will get nothing but django barf. To circumvent this you can simply create a template filter. Don’t be scared . . . it’s actually pretty simple. Let get to it:

  1. first off create the following folder and files:
  2. 1
    2
    3
    
    mkdir -p /path/to/project/appName/templatetags
    touch /path/to/project/an_app/templatetags/__init__.py
    touch /path/to/project/an_app/templatetags/appName_tags.py
  3. It is important that you make the directory/files inside of an app folder and name it exactly templatetags. the file appName_tags.py can be named anything as long as it has a .py extension.
  4. now paste the following code inside of appName_tags.py:
  5. 1
    2
    3
    4
    5
    6
    
    from django import template
    register = template.Library()
     
    @register.filter("mongo_id")
    def mongo_id(value):
        return str(value._id)
  6. all that is left is to utilize this filter. to do this, we simply load it inside of the corresponding template and viola:
    1
    2
    3
    4
    5
    6
    
    <html>
     <body>
      {% load appName_tags %}
      <p>here is your mongodb record id: {{ object|mongo_id }}</>
     </body>
    </html>

tip: custom filters can also take two arguments instead of the one shown above. check out this example below (referenced from here):



8 Comments

  1. Jeff Terry wrote:

    Thanks for your post. I am new at programming and this is a big help.

  2. Thanks for your post. I am new at django and this got me straight.

  3. Alfred wrote:

    np. let me know if you guy’s find it useful.

  4. I saw this really great post today!

  5. ehcache.net wrote:

    MongoDB ID’s and Django templates…

    So. Ran into a little frustration using MongoDB with Django; if you try to represent the _id field of a mongo object using something like {{ mongo_object._id }} or {{ mongo_object.id }}, you will get nothing but django barf. To circumvent this you can …

  6. Claudiu wrote:

    thanks for this tutorial!
    I wanted to say that for me it did not work with “return str(value._id)” I had to write “return str(value.['_id'])”

  7. Jakob wrote:

    This “filter” works better: http://d-w.me/blog/2010/1/15/8/

    Got an error using your code:

    def mongo_id(value):
    return str(value._id)