Cycle an arrangement of a MongoDB object in Python with Django

2

I'm trying to cycle an array that comes from a node in mongoDB, this is Mongo's object:

{
  "nombre": "Sebastián Yatra",
  "paises":["México","Argentina","Perú"]
}

The view controller is this

from django.shortcuts import render
from pymongo import MongoClient

def paises( req ):
  client = MongoClient()
  obj = { 'obj': client['mydb']['paises'].find() }
  return render( req, 'index.html', obj )

This is how I'm cycling in the view with Django

<h5>{{ obj.nombre }}</h5> #aquí si imprime Sebastián Yatra
<ul>
{% for pais in obj.paises %}
  <li>{{ pais[0] }}</li>
{% endfor %}
</ul>
<p>{{ len(obj.paises) }} encontados</p>

First he tells me

  

Could not parse this remainder: 'obj.paises' from 'len (obj.paises)'

And if I remove the line it says

  

Could not parse this remainder '[0]' from 'country [0]'

I'm still a novice with Python, my experience tells me that first I must declare a variable that increases type pais[i] but I do not know where to declare i = 0, and then where to increase it.

What can I do with these 2 erors?

    
asked by Alberto Siurob 03.08.2018 в 22:02
source

1 answer

3

First, with % for pais in obj.paises % you are already iterating over the list so that pais is the item in turn ("Mexico", "Argentina", "Peru", etc). You do not need to "index" about pais , just:

<li>{{ pais }}</li>

On the other hand, to show the length of the list you can use the built-in length :

<p>{{ obj.paises|length }} encontrados</p>

Therefore your template should look something like this:

<h5>{{ obj.nombre }}</h5>    
<ul>
  {% for pais in obj.paises %}
    <li>{{pais}}</li>
  {% endfor %}
</ul>    
<p>{{ obj.paises|length }} encontrados</p>

Which for your example would show us:

<html>
    <head>
    </head>
    <body>
        <h5>Sebastián Yatra</h5>
        <ul>
            <li>México</li>
            <li>Argentina</li>
            <li>Perú</li>
        </ul>
        <p>3 encontrados</p>
    </body>
</html>
    
answered by 03.08.2018 / 23:37
source