Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - For loop using Jinja and PyMongo repeating the same output for an entire dict

I am trying to print who a friend request has come from. To do so I have this app.route:

@app.route("/friend_requests", methods=["GET", "POST"])        
def friend_requests():
    user = session["user"] or None
    find_request = mongo.db.friend_requests.find_one({"friend_request_to": user})
    print(find_request)
    return render_template("friend_requests.html", find_request=find_request)

I am then adding this to a for loop in HTML using Jinja:

{% for find_requests in find_request %}
<span>from {{ find_request.friend_request_from }}</span>
{% endfor %}

The print(find_request) output in the terminal is this:

{'_id': ObjectId('600d281ec3957da9d448b845'), 'friend_request_from': 'admin2', 'friend_request_to': 'test3'}

And the output into the HTML (I will flash it up later when I get this right) is this:

 from admin2 from admin2 from admin2 

The loop seems to repeat for every item in the collection.

What I really want is the loop to find every time a user friend request is sent to this logged in user. In this case, for testing purposes, only one request has been sent.

How do I get the loop to print just the friend_request_from item in the collection?

question from:https://stackoverflow.com/questions/65871793/for-loop-using-jinja-and-pymongo-repeating-the-same-output-for-an-entire-dict

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I decided to beef up the route:

@app.route("/friend_requests/<user>", methods=["GET", "POST"])        
def friend_requests(user):
    user = session["user"]
    find_request = mongo.db.friend_requests.find({"friend_request_to": user})
    print(user)
    print(find_request)
    return render_template("friend_requests.html", find_request=find_request)

Part of the problem was the variable naming - I was confusing myself.

{% for x in find_request %}
<li>
    <div class="collapsible-header teal lighten-5">
        <i class="fas fa-chevron-circle-down blue-text text-darken-3"></i>
        <strong>{{ x.friend_request_from }}</strong>
    </div>
</li>
{% endfor %}

(slightly styled, but the loop remains the same).

This solves for the entire output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...