I'm making a web application using mongodb and django in Python, but I've come across a situation where I want to display the id to identify the item obtained from mongodb that repeats in the template.
I thought about the method of writing {{item._id}}
in the template, but since ʻitem.id is
" id": {"$ oid": "54cac41fe4b0b3c7e59cff77"} `, It cannot be displayed as it is.
Therefore, I decided to display it by adding a filter to the template.
Make the directory structure as follows. Create a directory called templatetags
.
|-view.py
|-templatetags/
| |- __init__.py
| |- filter.py
|
|-template/
|- template.html
It seems that __init__.py
needs to be written by promise in order to recognize this directory (templatetags) as a package.
__init__.py
#OK in the sky
Describe the contents of the filter in filter.py
. Here, the value of _id
is output as a character string.
filter.py
from django import template
register = template.Library()
@register.filter("mongo_id")
def mongo_id(value):
return str(value['_id'])
template.html
looks like this, and it seems that you can write it in the form of{{object | filter}}
. You need to load the package you want to use.
template.html
{% load filter %}
{% for item in items %}
<input type="hidden" name="id" value="{{item|mongo_id}}"/>
{% endfor %}
Recommended Posts