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:
- first off create the following folder and files:
- 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.
- now paste the following code inside of appName_tags.py:
- 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>
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 |
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) |
tip: custom filters can also take two arguments instead of the one shown above. check out this example below (referenced from here):



you bohbah!
Thanks for your post. I am new at programming and this is a big help.
Thanks for your post. I am new at django and this got me straight.
np. let me know if you guy’s find it useful.
I saw this really great post today!
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 …
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'])”
sorry for the typo, it’s “return str(value['_id'])”
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)