Issue
I am new to web development and can't figure out why the data from my SQLite database isn't being rendered unless I include lines of code that cause it to be paginated.
Code without pagination:
@tools.route("/toolkit/feedback/user/<string:username>", methods=['GET', 'POST'])
@login_required
def feedback(username):
user = User.query.filter_by(username=username).first_or_404()
feedback = Feedback.query.filter_by(author=user).all()
return render_template("comments.html", feedback=feedback, user=user)
Code with pagination:
@tools.route("/toolkit/feedback/user/<string:username>", methods=['GET', 'POST'])
@login_required
def feedback(username):
page = request.args.get('page', 1, type=int)
user = User.query.filter_by(username=username).first_or_404()
feedback = Feedback.query.filter_by(author=user)\
.paginate(page=page, per_page=10)
return render_template("comments.html", feedback=feedback, user=user)
HTML/Jinja2:
{% extends 'layout.html' %}
{% block content %}
<ul class="list-group list-group-flush">
{% for teacher_feedback in feedback.items %}
<li class="list-group-item">{{ teacher_feedback.comment }}</li>
{% endfor %}
</ul>
{% for page_num in feedback.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if feedback.page == page_num %}
<a class="btn btn-info mb-4" href="{{ url_for('tools.feedback', username=user.username, page=page_num) }}">{{ page_num }}</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{{ url_for('tools.feedback', username=user.username, page=page_num) }}">{{ page_num }}</a>
{% endif %}
{% else %}
...
{% endif %}
{% endfor %}
{% endblock content %}
Solution
The paginate
function returns a Pagination
object which has the iter_pages
method. A standard SQLAlchemy query doesn't have this method which is why you don't see anything when you try iterate over feedback
in your template.
As this line feedback = Feedback.query.filter_by(author=user).all()
gives you a list
, in the HTML for you non-paginate method you could try as a test:
{% for f in feedback %}
<p>{{f.AN_ATTRIBUTE_OF_FEEDBACK}}</p>
{% endfor %}
Answered By - PGHE
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.