pythonmongodbflaskpymongoflask-pymongo

Flask-PyMongo. How to display all entries from python to html?


one entry contains: title, link, time, text. How to display all entries from python to html? I tried a lot of options, but I couldn't find the correct syntax. Last try:

App.py:

from flask import Flask, render_template, jsonify
from flask_pymongo import PyMongo

app = Flask(__name__)

app.config["MONGO_URI"] = "mongodb+srv://..."
mongo = PyMongo(app)


@app.route('/', methods=['GET'])
def index():
    link = mongo.db.archive.find({"link"})
    title = mongo.db.archive.find({"title"})
    text = mongo.db.archive.find({"text"})
    time = mongo.db.archive.find({"time"})

    return render_template('index.html', title=title, link=link, time=time, text=text)

if __name__ == "__main__":
    app.run(debug=True)

HTML

<ul>
    {% for title in titles %}
    <li>
        <label>
            <span>  TITLE:  {{title}}  <br>  HREF:  {{link}}  <br>  DATE:  {{time_date}} <br>  TEXT:  {{text_stat}}  </span>
        </label>
    </li>
    {% endfor %}
</ul>

Solution

  • Please consider my comment.

    You are querying it wrong, the first argument to the find is the filter, second is projection.

    I think you need to do like this:

    app.py:

    @app.route('/', methods=['GET'])
    def index():
        cur = mongo.db.archive.find({}, {'link': 1, 'title': 1, 'text': 1, 'time': 1, '_id': 0})
        return render_template('index.html', cur=list(cur))
    

    index.html

    <ul>
        {% for item in cur %}
        <li>
            <label>
                <span>  TITLE:  {{item.title}}  <br>  HREF:  {{item.link}}  <br>  DATE:  {{item.time}} <br>  TEXT:  {{item.text}}  </span>
            </label>
        </li>
        {% endfor %}
    </ul>