Skip to content
Advertisement

get mongodb “_id” in django template

My question is related to this question.

I am trying to display all the _id of mongo database in django template from last 2 days but unable to get it.

This is the error:

error

This is the code I am trying:

views.py

register = template.Library()
port = 27019
client = MongoClient(port=port)
mydb = client.catalogDB
data = mydb.productCatalog  

def index(request):
   values = data.find()
   @register.filter("mongo_id")
   def mongo_id(value):
      return str(value['_id'])
   return render(request, 'product.html', {"values":values})

product.html

<ul class="row catalog-list">
    {% for value in values %}    
    <li class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
       <div>
          <img src={{value.image_url_medium}}>
          <label>
            <input type="checkbox" name="sync-check" class="catalog-checkbox">
          </label>
        </div>
        <div>
          {% csrf_token %}
          <h4 class="ellipsis-text catalog-item-name" tooltip={{value.name}}><span class="catalogProductId">{{value.name}}</span></h4>
          {% load views %}
          <h5 >Product Id: {{ object|mongo_id }}</h5>
          <h5>Category:{{value.catagory}}</h5>
          <h5>Best Price: {{value.best_price}}</h5>
          <h5>Best Price Vendor: {{value.best_price_vendor}}</h5>
          <h5 class="ellipsis-text">Link:
            <a href={{value.best_price_vendor_url}}>{{value.best_price_vendor_url}}</a>
          </h5>
        </div>
    </li>
    {% endfor %}
    <h2 class="message">Sorry no records found</h2>
</ul>

Though, I tried changing the name to static, cache etc, but still no luck.

Advertisement

Answer

template tag written in app/templatetag folder not in view of app.

https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement