You can get the ID of a MongoDB document using the _id
attribute. However using {{ object._id }}
in a Django template, makes it throw an error saying it couldn't find the _id attribute.
To solve this, you must create a custom template tag for your app and use that to get the _id.
Inside your app folder, create a templatetags folder and create some python file eg:appname_tags.py.
The directory structure would be something like this
/projectdir
/appdir
/templatetags
__init__.py
appname_tags.py
models.py
views.py
Inside the appname_tags.py paste the following code
from django import template
register = template.Library()
@register.filter("mongo_id")
def mongo_id(value):
return str(value['_id'])
Now you can use this new custom template tag in your templates by loading the tag module and passing the mongo document object to it.
<html>
<body>
{% load appname_tags %}
<p>here is your mongodb record id: {{ object|mongo_id }}</>
</body>
</html>
Remember, the app should be in the INSTALLED_APPS
settings variable in settings.py
for django to load the template tag.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…