Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

django - Get object id of document already in mongoDB collection in Python

I have a collection in mongodb in which I have already inserted the documents.Now I want to update a document entry and I want to retrieve the document ID in the django template,like I am using checkbox alongside of the entry in the HTML.I want to give individual box a unique id which i plan to use same as the document id .. so HOW DO I RETRIEVE THE DOCUMENT ID IN THE DJANGO TEMPLATE ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...