Chapter 9: Pagination (v0.9)

This commit is contained in:
Miguel Grinberg 2017-09-17 22:41:40 -07:00
parent f2f48af840
commit f525e4c270
No known key found for this signature in database
GPG Key ID: 36848B262DF5F06C
7 changed files with 79 additions and 23 deletions

View File

@ -46,3 +46,8 @@ class EditProfileForm(FlaskForm):
user = User.query.filter_by(username=self.username.data).first() user = User.query.filter_by(username=self.username.data).first()
if user is not None: if user is not None:
raise ValidationError('Please use a different username.') raise ValidationError('Please use a different username.')
class PostForm(FlaskForm):
post = TextAreaField('Say something', validators=[DataRequired()])
submit = SubmitField('Submit')

View File

@ -3,8 +3,8 @@ from flask import render_template, flash, redirect, url_for, request
from flask_login import login_user, logout_user, current_user, login_required from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse from werkzeug.urls import url_parse
from app import app, db from app import app, db
from app.forms import LoginForm, RegistrationForm, EditProfileForm from app.forms import LoginForm, RegistrationForm, EditProfileForm, PostForm
from app.models import User from app.models import User, Post
@app.before_request @app.before_request
@ -14,21 +14,41 @@ def before_request():
db.session.commit() db.session.commit()
@app.route('/') @app.route('/', methods=['GET', 'POST'])
@app.route('/index') @app.route('/index', methods=['GET', 'POST'])
@login_required @login_required
def index(): def index():
posts = [ form = PostForm()
{ if form.validate_on_submit():
'author': {'username': 'John'}, post = Post(body=form.post.data, author=current_user)
'body': 'Beautiful day in Portland!' db.session.add(post)
}, db.session.commit()
{ flash('Your post is now live!')
'author': {'username': 'Susan'}, return redirect(url_for('index'))
'body': 'The Avengers movie was so cool!' page = request.args.get('page', 1, type=int)
} posts = current_user.followed_posts().paginate(
] page, app.config['POSTS_PER_PAGE'], False)
return render_template('index.html', title='Home', posts=posts) next_url = url_for('explore', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('explore', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title='Home', form=form,
posts=posts.items, next_url=next_url,
prev_url=prev_url)
@app.route('/explore')
@login_required
def explore():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.timestamp.desc()).paginate(
page, app.config['POSTS_PER_PAGE'], False)
next_url = url_for('explore', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('explore', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title='Explore', posts=posts.items,
next_url=next_url, prev_url=prev_url)
@app.route('/login', methods=['GET', 'POST']) @app.route('/login', methods=['GET', 'POST'])
@ -74,11 +94,15 @@ def register():
@login_required @login_required
def user(username): def user(username):
user = User.query.filter_by(username=username).first_or_404() user = User.query.filter_by(username=username).first_or_404()
posts = [ page = request.args.get('page', 1, type=int)
{'author': user, 'body': 'Test post #1'}, posts = user.posts.order_by(Post.timestamp.desc()).paginate(
{'author': user, 'body': 'Test post #2'} page, app.config['POSTS_PER_PAGE'], False)
] next_url = url_for('user', username=user.username, page=posts.next_num) \
return render_template('user.html', user=user, posts=posts) if posts.has_next else None
prev_url = url_for('user', username=user.username, page=posts.prev_num) \
if posts.has_prev else None
return render_template('user.html', user=user, posts=posts.items,
next_url=next_url, prev_url=prev_url)
@app.route('/edit_profile', methods=['GET', 'POST']) @app.route('/edit_profile', methods=['GET', 'POST'])

View File

@ -1,6 +1,6 @@
<table> <table>
<tr valign="top"> <tr valign="top">
<td><img src="{{ post.author.avatar(36) }}"></td> <td><img src="{{ post.author.avatar(36) }}"></td>
<td>{{ post.author.username }} says:<br>{{ post.body }}</td> <td><a href="{{ url_for('user', username=post.author.username) }}">{{ post.author.username }}</a> says:<br>{{ post.body }}</td>
</tr> </tr>
</table> </table>

View File

@ -10,6 +10,7 @@
<div> <div>
Microblog: Microblog:
<a href="{{ url_for('index') }}">Home</a> <a href="{{ url_for('index') }}">Home</a>
<a href="{{ url_for('explore') }}">Explore</a>
{% if current_user.is_anonymous %} {% if current_user.is_anonymous %}
<a href="{{ url_for('login') }}">Login</a> <a href="{{ url_for('login') }}">Login</a>
{% else %} {% else %}
@ -28,5 +29,5 @@
{% endif %} {% endif %}
{% endwith %} {% endwith %}
{% block content %}{% endblock %} {% block content %}{% endblock %}
</body> </body>
</html> </html>

View File

@ -2,7 +2,26 @@
{% block content %} {% block content %}
<h1>Hi, {{ current_user.username }}!</h1> <h1>Hi, {{ current_user.username }}!</h1>
{% if form %}
<form action="" method="post">
{{ form.hidden_tag() }}
<p>
{{ form.post.label }}<br>
{{ form.post(cols=32, rows=4) }}<br>
{% for error in form.post.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
{% endif %}
{% for post in posts %} {% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div> {% include '_post.html' %}
{% endfor %} {% endfor %}
{% if prev_url %}
<a href="{{ prev_url }}">Newer posts</a>
{% endif %}
{% if next_url %}
<a href="{{ next_url }}">Older posts</a>
{% endif %}
{% endblock %} {% endblock %}

View File

@ -23,4 +23,10 @@
{% for post in posts %} {% for post in posts %}
{% include '_post.html' %} {% include '_post.html' %}
{% endfor %} {% endfor %}
{% if prev_url %}
<a href="{{ prev_url }}">Newer posts</a>
{% endif %}
{% if next_url %}
<a href="{{ next_url }}">Older posts</a>
{% endif %}
{% endblock %} {% endblock %}

View File

@ -13,3 +13,4 @@ class Config(object):
MAIL_USERNAME = os.environ.get('MAIL_USERNAME') MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
ADMINS = ['your-email@example.com'] ADMINS = ['your-email@example.com']
POSTS_PER_PAGE = 25