Generating new HTML rows for each Document from firestore in python Django

Question:

I have a collection of documents in a Firestore database. I want to create a web form to display all the documents and their fields. I started by streaming all the documents using:

    docs = db.collection(u'users').stream() 

and then appending all the docs IDs to a list and pass it to the HTML file as follows


   def index(request):
   myIDs =[]
   db = firestore.Client()
   docs = db.collection(u'users').stream() 
   for doc in docs:
       myIDs.append(f'{doc.id}')


return render(request, 'index.html', {
       "weight":"abc",
       "firstRow":myIDs[0],
       "secondRow":myIDs[1],
       "thirdRow":myIDs[2],
       "fourthRow":myIDs[3],
       "fifthRow":myIDs[4],
       "sixthRow":myIDs[5],
       "seventhRow":myIDs[6],

   })

After that, I created a very basic HTML code just to display the document IDs as follows:

<html>
   <body>    
           <table border="1" cellpadding = "5" cellspacing="5"> 
               <tr>
                   <td>{{ firstRow }}</td>
                   <tr>
                       <td>{{ secondRow }}</td>
                   </tr>
                   <tr>
                       <td>{{ thirdRow }}</td>
                   </tr>
                   <tr>
                       <td>{{ fourthRow }}</td>
                   </tr>
                   <tr>
                       <td>{{ fifthRow }}</td>
                   </tr>
                   <tr>
                       <td>{{ sixthRow }}</td>
                   </tr>
                   <tr>
                       <td>{{ seventhRow }}</td>
                   </tr>
               </tr>
           </table>
   </body>
</html>

Till this point I am just doing very basic stuff. But I am new to Django and Python for the Web, so my question is: how can I make it so that the HTML rows become adaptive based on the number of documents?
For example, if I have 20 documents, I want to make it so that it will generate the 20 rows and pass each of the document IDs to one row, and so on.

Asked By: taha khamis

||

Answers:

This is fairly simple in Django

You can pass the list MyIDs as a context variable and let your template do the heavy lifting

return render(request, 'index.html', {
       "weight":"abc", 
       "myIDs": myIDs    
   })

Then in your template

<table border="1" cellpadding = "5" cellspacing="5"> 
{% for id in myIDs %}
    <tr> 
       <td>{{ id }}</td>
    </tr>
{% endfor %}
</table>

(I suspect you can make this even simpler by passing docs as a context variable, which would let you do

{% for doc in docs %}
    <tr> 
       <td>{{ doc.id }}</td>
       <td>{{ doc.title }}</td>
    </tr>
{% endfor %}
</table>

but I’m not 100% familiar with the output of stream() )

Answered By: SamSparx