Home > Software design >  Pass list of object to HTML page for looping and display data as list of object
Pass list of object to HTML page for looping and display data as list of object

Time:05-01

I'm trying to pass the list of object to HTML for looping to render the data fetch from MongoDB

Approach tried:

  1. Created a global variable as list of object. Fetched the data from the MongoDB and set the data to global variable

    And tried to fetch it directly but this is not accessible means no error and there was no data as well.

  2. Passing the fetch list of object as render during def of index(request)

    x=mycol.find()
    
    downloadData=list(x)
    
    return render(request, 'index.html',downloadData)
    

    error:

    File "C:\xxx\views.py", line 30, in index return render(request, 'index.html',downloadData)

    AttributeError: 'list' object has no attribute 'dict'

    HTML Code:

    {% for d in downloadData %}
            <div >
              <h2>I Love Food</h2>
              <p>Food is my passion. Lorem ipsum dolor sit amet, consectetur adipiscing elit, </p>
            </div>
     {% endfor %}
    

Could anyone point what i am doing wrong in both approaches?

If you could point to correct link will be helpful

CodePudding user response:

You should pass your data as dictionary in context like this,

return render(request, 'index.html',{'downloadData'=downloadData})

and in HTML, you can access it like this,

{% for d in downloadData %}

        <div >
          <h2>d</h2>
        </div>
 {% endfor %}

CodePudding user response:

I think you should pass the downloadData as an argument like below

return render(request, 'index.html', {'downloadData': downloadData})
  • Related