Display data from mongodb to html page in realtime

Viewed 51

I'm working on a python project, and I want to fetch and display data from mongodb in real-time, for example, display the new data in an html table page as soon as it's pushed to the DB, and the other data will be displayed while refreshing the page. Any help is highly appreciated.

this is my view.py :

def datatable_view(request):
    if request.method =='POST':
        form = Scraping(request.POST)
        if form.is_valid():
            subject=form.cleaned_data['subject']
            #run python code of scraping
            scrap(subject)
            #add the products scraped to the database
            client = pymongo.MongoClient("mongodb://localhost:27017/")
            # use variable names for db and collection reference
            db= client["db2"]
            col = db[subject]
            products = col.find()
            context = {'products' : products}
            #open datatable html and display all the data from database
            return render(request,'datatable.html', context)
    return

this is my html table page datatable.html :

<table id="scrap" class="table table-striped table-bordered" style="width:100%">
 <tbody>
                {% for product in products %}
                <tr>
                    <td> {{ product.Title }} </td>
                    <td> {{ product.Price }} </td>
                    <td> {{ product.Currency }} </td>
                    <td> {{ product.Stars }} </td>
                    <td> {{ product.Orders}} </td>
                    <td> {{ product.Shipcost }} </td>
                    <td> {{ product.Supplier }} </td>
                    <td><a href="{{product.Productlinks }}"> Click here</a></td>
                </tr>
              {% endfor %}
              </tbody>
            </table>
1 Answers

col.find() returns pymongo.cursor.Cursor object.

To fix the problem, you need to cast the cursor to the list: list(products).

And return list of dict.

Related