2018-01-30T18:07:32Z

The Flask Mega-Tutorial Part IX: Pagination

This is the ninth installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to paginate lists of database entries.

For your reference, below is a list of the articles in this series.

Note 1: If you are looking for the legacy version of this tutorial, it's here.

Note 2: If you would like to support my work on this blog, or just don't have patience to wait for weekly articles, I am offering the complete version of this tutorial packaged as an ebook or a set of videos. For more information, visit courses.miguelgrinberg.com.

In Chapter 8 I have made several database changes necessary to support the "follower" paradigm that is so popular with social networks. With that functionality in place, I'm ready to remove the last piece of scaffolding that I have put in place in the beginning, the fake posts. In this chapter the application will start accepting blog posts from users, and also deliver them in the home and profile pages.

The GitHub links for this chapter are: Browse, Zip, Diff.

Submission of Blog Posts

Let's start with something simple. The home page needs to have a form in which users can type new posts. First I create a form class:

app/forms.py: Blog submission form.

class PostForm(FlaskForm):
    post = TextAreaField('Say something', validators=[
        DataRequired(), Length(min=1, max=140)])
    submit = SubmitField('Submit')

Next, I can add this form to the template for the main page of the application:

app/templates/index.html: Post submission form in index template

{% extends "base.html" %}

{% block content %}
    <h1>Hi, {{ current_user.username }}!</h1>
    <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>
    {% for post in posts %}
    <p>
    {{ post.author.username }} says: <b>{{ post.body }}</b>
    </p>
    {% endfor %}
{% endblock %}

The changes in this template are similar to how previous forms were handled. The final part is to add the form creation and handling in the view function:

app/routes.py: Post submission form in index view function.

from app.forms import PostForm
from app.models import Post

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for('index'))
    posts = [
        {
            'author': {'username': 'John'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author': {'username': 'Susan'},
            'body': 'The Avengers movie was so cool!'
        }
    ]
    return render_template("index.html", title='Home Page', form=form,
                           posts=posts)

Let's review the changes in this view function one by one:

  • I'm now importing the Post and PostForm classes
  • I accept POST requests in both routes associated with the index view function in addition to GET requests, since this view function will now receive form data.
  • The form processing logic inserts a new Post record into the database.
  • The template receives the form object as an additional argument, so that it can render the text field.

Before I continue, I wanted to mention something important related to processing of web forms. Notice how after I process the form data, I end the request by issuing a redirect to the home page. I could have easily skipped the redirect and allowed the function to continue down into the template rendering part, since this is already the index view function.

So, why the redirect? It is a standard practice to respond to a POST request generated by a web form submission with a redirect. This helps mitigate an annoyance with how the refresh command is implemented in web browsers. All the web browser does when you hit the refresh key is to re-issue the last request. If a POST request with a form submission returns a regular response, then a refresh will re-submit the form. Because this is unexpected, the browser is going to ask the user to confirm the duplicate submission, but most users will not understand what the browser is asking them. But if a POST request is answered with a redirect, the browser is now instructed to send a GET request to grab the page indicated in the redirect, so now the last request is not a POST request anymore, and the refresh command works in a more predictable way.

This simple trick is called the Post/Redirect/Get pattern. It avoids inserting duplicate posts when a user inadvertently refreshes the page after submitting a web form.

Displaying Blog Posts

If you recall, I created a couple of fake blog posts that I've been displaying in the home page for a long time. These fake objects are created explicitly in the index view function as a simple Python list:

    posts = [
        { 
            'author': {'username': 'John'}, 
            'body': 'Beautiful day in Portland!' 
        },
        { 
            'author': {'username': 'Susan'}, 
            'body': 'The Avengers movie was so cool!' 
        }
    ]

But now I have the followed_posts() method in the User model that returns a query for the posts that a given user wants to see. So now I can replace the fake posts with real posts:

app/routes.py: Display real posts in home page.

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    # ...
    posts = current_user.followed_posts().all()
    return render_template("index.html", title='Home Page', form=form,
                           posts=posts)

The followed_posts method of the User class returns a SQLAlchemy query object that is configured to grab the posts the user is interested in from the database. Calling all() on this query triggers its execution, with the return value being a list with all the results. So I end up with a structure that is very much alike the one with fake posts that I have been using until now. It's so close that the template does not even need to change.

Making It Easier to Find Users to Follow

As I'm sure you noticed, the application as it is does not do a great job at letting users find other users to follow. In fact, there is actually no way to see what other users are there at all. I'm going to address that with a few simple changes.

I'm going to create a new page that I'm going to call the "Explore" page. This page will work like the home page, but instead of only showing posts from followed users, it will show a global post stream from all users. Here is the new explore view function:

app/routes.py: Explore view function.

@app.route('/explore')
@login_required
def explore():
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('index.html', title='Explore', posts=posts)

Did you notice something odd in this view function? The render_template() call references the index.html template, which I'm using in the main page of the application. Since this page is going to be very similar to the main page, I decided to reuse the template. But one difference with the main page is that in the explore page I do not want to have a form to write blog posts, so in this view function I did not include the form argument in the template call.

To prevent the index.html template from crashing when it tries to render a web form that does not exist, I'm going to add a conditional that only renders the form if it is defined:

app/templates/index.html: Make the blog post submission form optional.

{% extends "base.html" %}

{% block content %}
    <h1>Hi, {{ current_user.username }}!</h1>
    {% if form %}
    <form action="" method="post">
        ...
    </form>
    {% endif %}
    ...
{% endblock %}

I'm also going to add a link to this new page in the navigation bar:

app/templates/base.html: Link to explore page in navigation bar.

        <a href="{{ url_for('explore') }}">Explore</a>

Remember the _post.html sub-template that I have introduced in Chapter 6 to render blog posts in the user profile page? This was a small template that was included from the user profile page template, and was separate so that it can also be used from other templates. I'm now going to make a small improvement to it, which is to show the username of the blog post author as a link:

app/templates/_post.html: Show link to author in blog posts.

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

I can now use this sub-template to render blog posts in the home and explore pages:

app/templates/index.html: Use blog post sub-template.

    ...
    {% for post in posts %}
        {% include '_post.html' %}
    {% endfor %}
    ...

The sub-template expects a variable named post to exist, and that is how the loop variable in the index template is named, so that works perfectly.

With these small changes, the usability of the application has improved considerably. Now a user can visit the explore page to read blog posts from unknown users and based on those posts find new users to follow, which can be done by simply clicking on a username to access the profile page. Amazing, right?

At this point I suggest you try the application once again, so that you experience these last user interface improvements.

Blog Posts

Pagination of Blog Posts

The application is looking better than ever, but showing all of the followed posts in the home page is going to become a problem sooner rather than later. What happens if a user has a thousand followed posts? Or a million? As you can imagine, managing such a large list of posts will be extremely slow and inefficient.

To address that problem, I'm going to paginate the post list. This means that initially I'm going to show just a limited number of posts at a time, and include links to navigate through the entire list of posts. Flask-SQLAlchemy supports pagination natively with the paginate() query method. If for example, I want to get the first twenty followed posts of the user, I can replace the all() call that terminates the query with:

>>> user.followed_posts().paginate(1, 20, False).items

The paginate method can be called on any query object from Flask-SQLAlchemy. It takes three arguments:

  • the page number, starting from 1
  • the number of items per page
  • an error flag. If True, when an out of range page is requested a 404 error will be automatically returned to the client. If False, an empty list will be returned for out of range pages.

The return value from paginate is a Pagination object. The items attribute of this object contains the list of items in the requested page. There are other useful things in the Pagination object that I will discuss later.

Now let's think about how I can implement pagination in the index() view function. I can start by adding a configuration item to the application that determines how many items will be displayed per page.

config.py: Posts per page configuration.

class Config(object):
    # ...
    POSTS_PER_PAGE = 3

It is a good idea to have these application-wide "knobs" that can change behaviors in the configuration file, because then I can go to a single place to make adjustments. In the final application I will of course use a larger number than three items per page, but for testing it is useful to work with small numbers.

Next, I need to decide how the page number is going to be incorporated into application URLs. A fairly common way is to use a query string argument to specify an optional page number, defaulting to page 1 if it is not given. Here are some example URLs that show how I'm going to implement this:

  • Page 1, implicit: http://localhost:5000/index
  • Page 1, explicit: http://localhost:5000/index?page=1
  • Page 3: http://localhost:5000/index?page=3

To access arguments given in the query string, I can use the Flask's request.args object. You have seen this already in Chapter 5, where I implemented user login URLs from Flask-Login that can include a next query string argument.

Below you can see how I added pagination to the home and explore view functions:

app/routes.py: Followers association table

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    # ...
    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', form=form,
                           posts=posts.items)

@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)
    return render_template("index.html", title='Explore', posts=posts.items)

With these changes, the two routes determine the page number to display, either from the page query string argument or a default of 1, and then use the paginate() method to retrieve only the desired page of results. The POSTS_PER_PAGE configuration item that determines the page size is accessed through the app.config object.

Note how easy these changes are, and how little code is affected each time a change is made. I am trying to write each part of the application without making any assumptions about how the other parts work, and this enables me to write modular and robust applications that are easier to extend and to test, and are less likely to fail or have bugs.

Go ahead and try the pagination support. First make sure you have more than three blog posts. This is easier to see in the explore page, which shows posts from all users. You are now going to see just the three most recent posts. If you want to see the next three, type http://localhost:5000/explore?page=2 in your browser's address bar.

Page Navigation

The next change is to add links at the bottom of the blog post list that allow users to navigate to the next and/or previous pages. Remember that I mentioned that the return value from a paginate() call is an object of a Pagination class from Flask-SQLAlchemy? So far, I have used the items attribute of this object, which contains the list of items retrieved for the selected page. But this object has a few other attributes that are useful when building pagination links:

  • has_next: True if there is at least one more page after the current one
  • has_prev: True if there is at least one more page before the current one
  • next_num: page number for the next page
  • prev_num: page number for the previous page

With these four elements, I can generate next and previous page links and pass them down to the templates for rendering:

app/routes.py: Next and previous page links.

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    # ...
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('index', 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)

The next_url and prev_url in these two view functions are going to be set to a URL returned by url_for() only if there is a page in that direction. If the current page is at one of the ends of the collection of posts, then the has_next or has_prev attributes of the Pagination object will be False, and in that case the link in that direction will be set to None.

One interesting aspect of the url_for() function that I haven't discussed before is that you can add any keyword arguments to it, and if the names of those arguments are not referenced in the URL directly, then Flask will include them in the URL as query arguments.

The pagination links are being set to the index.html template, so now let's render them on the page, right below the post list:

app/templates/index.html: Render pagination links on the template.

    ...
    {% for post in posts %}
        {% include '_post.html' %}
    {% endfor %}
    {% if prev_url %}
    <a href="{{ prev_url }}">Newer posts</a>
    {% endif %}
    {% if next_url %}
    <a href="{{ next_url }}">Older posts</a>
    {% endif %}
    ...

This change adds two links below the post list on both the index and explore pages. The first link is labeled "Newer posts", and it points to the previous page (keep in mind I'm showing posts sorted by newest first, so the first page is the one with the newest content). The second link is labeled "Older posts" and points to the next page of posts. If any of these two links is None, then it is omitted from the page, through a conditional.

Pagination

Pagination in the User Profile Page

The changes for the index page are sufficient for now. However, there is also a list of posts in the user profile page, which shows only posts from the owner of the profile. To be consistent, the user profile page should be changed to match the pagination style of the index page.

I begin by updating the user profile view function, which still had a list of fake post objects in it.

app/routes.py: Pagination in the user profile view function.

@app.route('/user/<username>')
@login_required
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    page = request.args.get('page', 1, type=int)
    posts = user.posts.order_by(Post.timestamp.desc()).paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('user', username=user.username, page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('user', username=user.username, page=posts.prev_num) \
        if posts.has_prev else None
    form = EmptyForm()
    return render_template('user.html', user=user, posts=posts.items,
                           next_url=next_url, prev_url=prev_url, form=form)

To get the list of posts from the user, I take advantage of the fact that the user.posts relationship is a query that is already set up by SQLAlchemy as a result of the db.relationship() definition in the User model. I take this query and add a order_by() clause so that I get the newest posts first, and then do the pagination exactly like I did for the posts in the index and explore pages. Note that the pagination links that are generated by the url_for() function need the extra username argument, because they are pointing back at the user profile page, which has this username as a dynamic component of the URL.

Finally, the changes to the user.html template are identical to those I made on the index page:

app/templates/user.html: Pagination links in the user profile template.

    ...
    {% for post in posts %}
        {% include '_post.html' %}
    {% endfor %}
    {% if prev_url %}
    <a href="{{ prev_url }}">Newer posts</a>
    {% endif %}
    {% if next_url %}
    <a href="{{ next_url }}">Older posts</a>
    {% endif %}

After you are done experiment with the pagination feature, you can set the POSTS_PER_PAGE configuration item to a more reasonable value:

config.py: Posts per page configuration.

class Config(object):
    # ...
    POSTS_PER_PAGE = 25

112 comments

  • #51 jg1212 said 2018-12-06T03:33:08Z

    Hi Miguel, Amazing tutorial. You are a great teacher. Not sure if you get to this later in the tutorial, but how would you recommend preventing the following integer overflow attack? OverflowError: Python int too large to convert to SQLite INTEGER 127.0.0.1 - - [05/Dec/2018 22:31:20] "GET /index?page=9999999999999999999 HTTP/1.1" 500 - Thanks, JG

  • #52 Miguel Grinberg said 2018-12-06T11:10:03Z

    @ jg1212: Why would this be an attack? All I see is that the client sent a bad argument, and the server errored. The correct error would have been 400, not 500, but other than that I need help in seeing the potential danger. The page number could be validated, the pagination object returned by Flask-SQLAlchemy tells you how many total pages there are.

  • #53 Vingoldo Sirimboldi said 2018-12-07T14:03:33Z

    Hi Miguel,

    Thank you for this amazing tutorial! It is super helpful and well explained!

    I have a question regarding simultaneous pagination and query of a database. I'm trying to build a page that contains a form in order to query data from the database table, like the following:

    @app.route('/ciao', methods=['GET', 'POST']) def ciao(): form = BlaBlaForm() page = request.args.get('page', 1, type=int) if form.validate_on_submit(): ### BUILD query_dict from form fields data dbitems = initquery.join(...).filter_by(**query_dict).order_by(...).paginate(page, app.config['CIAO_PER_PAGE'], False) else: dbitems = Foo.query.join(...).order_by(...).paginate(page, app.config['CMM_PER_PAGE'], False) next_url = url_for('ciao', page=dbitems.next_num) if dbitems.has_next else None prev_url = url_for('ciao', page=dbitems.prev_num) if dbitems.has_prev else None return render_template('ciao.html', form=form, dbitems=dbitems.items, next_url=next_url, prev_url=prev_url, title='CIAO')

    The pagination works fine for the first page, however the filter is lost for the following pages. Do you have any suggestions on how to cleverly fix it?

    Thank you in advance!

  • #54 Miguel Grinberg said 2018-12-07T14:13:55Z

    @Vingoldo: you need to preserve the form fields somehow. For example, if you submit the form as a GET request, then the fields will be in the query string of the URL. In that case you can include the fields again in the links to move through the pages.

  • #55 Steve Fibich said 2018-12-09T18:10:14Z

    I received the following error once I implemented the paginate feature 'Pagination' object is not iterable flask, this tripped me up for a while until I realized you can call the .items method on this object to get an iterable object. Hope this helps anyone else who has encounters this issue. Still not to sure why I saw this issue and it looks like no one else has encountered it. Maybe a newer version of SQL Alchemy.

  • #56 wedojava said 2018-12-12T03:31:45Z

    Hi Miguel,

    Thanks for your helpful tutorial!

    I have a question regarding pagination by hard query object. I'm make a page that contains a form in order to query data from the database table, like the following:

    words_email = ["%" + form.email.data + "%"] rule = and_(*[LogImported.sender_address.like(w) for w in words_email]) logs = LogImported.query.filter(rule) pagination = logs.paginate(page, per_page=50, error_out=True)

    then, first request after,I can get the right page,but click any other page number links,will return 404 error. I tracked,and find out the logs or filter() has something wrong,if I cut filter,it work right.but how to use filter?I think, it must have a right way to paginate hard query result like use filter.

    I read your comments before,how can " lazy='dynamic' " use at this case? or, it can not use at this place?

    Thanks for your attention,I tried to google and stackoverflow and read documents, but cannot find out the right way to solve it.Except you may help me.

    Thank you.

  • #57 Miguel Grinberg said 2018-12-12T15:22:40Z

    @wedojava: you are asking the pagination to return an error with the "error_out=True' argument. Set it to False if you prefer to receive empty pages.

  • #58 wedojava said 2018-12-13T04:38:16Z

    yes,I tried this option before,and received empty pages,any pages cannot receive right page.I know why this error happened,I know the number of results are less than the size of the first page.but I don't know how to solve it.

  • #59 Miguel Grinberg said 2018-12-13T12:35:00Z

    @wedojava: what are you trying to solve? If you go beyond the list of results you are either going to get an empty page or a 404, what other way you want that case handled? If you want to prevent this from happening, make sure you don't offer a Next Page link when you are looking at the last page.

  • #60 M said 2019-01-23T05:38:21Z

    Hello Miguel,

    After setting up followers and working on pagination I ran into an error. I'm not sure where the problem lies.

    This is the error output.

    (venv) MacBook-Pro:microblog m$ /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 /Users/m/Development/microblog/test.py Traceback (most recent call last): File "/Users/m/Development/microblog/test.py", line 3, in from app import app, db File "/Users/m/Development/microblog/app/init.py", line 13, in from app import errors, models, routes File "/Users/m/Development/microblog/app/errors.py", line 2, in from app import app, db ImportError: cannot import name 'app' from 'app' (/Users/m/Development/microblog/app/init.py)

    I have read online the it could be calling something before its been initialized or that its a circular import but I am at a loss.

  • #61 Miguel Grinberg said 2019-01-23T13:31:18Z

    @M: Yes, the circular import is clearly seen in your stack trace: test.py imports app and db from the app package. The app package's init.py module imports errors.py, and errors.py imports once again app and db.

    The solution is to move the "from app import errors, models, routes" line in app/init.py down in the file, in a place after both app and db have been defined.

  • #62 JOHN said 2019-02-16T10:02:49Z

    @miguelgrinberg Good work on ur flask mega tutorials. I am currently on The Flask Mega-Tutorial Part IX: Pagination, I encountered a problem that i can't solve. I compare my codes with yours and everything seem to be ok. Sorry I'm telling u about this on twitter This is the error message:

    [2019-02-16 10:42:57,732] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1236, in _execute_context cursor, statement, parameters, context File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 536, in do_execute cursor.execute(statement, parameters) sqlite3.OperationalError: no such column: post.timestamp

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last): File "c:\users\philejohn\everyflask\venv\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\users\philejohn\everyflask\venv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\philejohn\everyflask\venv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\philejohn\everyflask\venv\lib\site-packages\flask_compat.py", line 35, in reraise raise value File "c:\users\philejohn\everyflask\venv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\users\philejohn\everyflask\venv\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functionsrule.endpoint File "c:\users\philejohn\everyflask\venv\lib\site-packages\flask_login\utils.py", line 261, in decorated_view return func(args, *kwargs) File "C:\Users\philejohn\EveryFlask\app\routes.py", line 30, in index posts = current_user.followed_posts().all() File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\orm\query.py", line 2925, in all return list(self) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3081, in iter return self._execute_and_instances(context) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3106, in _execute_and_instances result = conn.execute(querycontext.statement, self._params) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 980, in execute return meth(self, multiparams, params) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 273, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1099, in _execute_clauseelement distilled_params, File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1240, in _execute_context e, statement, parameters, cursor, context File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1458, in _handle_dbapi_exception util.raise_from_cause(sqlalchemy_exception, exc_info) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 296, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 276, in reraise raise value.with_traceback(tb) File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1236, in _execute_context cursor, statement, parameters, context File "c:\users\philejohn\everyflask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 536, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: post.timestamp [SQL: 'SELECT anon_1.post_id AS anon_1_post_id, anon_1.post_body AS anon_1_post_body, anon_1.post_timestamp AS anon_1_post_timestamp, anon_1.post_user_id AS anon_1_post_user_id \nFROM (SELECT post.id AS post_id, post.body AS post_body, post.timestamp AS post_timestamp, post.user_id AS post_user_id \nFROM post JOIN followers ON followers.followed_id = post.user_id \nWHERE followers.follower_id = ? UNION SELECT post.id AS post_id, post.body AS post_body, post.timestamp AS post_timestamp, post.user_id AS post_user_id \nFROM post \nWHERE post.user_id = ?) AS anon_1 ORDER BY anon_1.post_timestamp DESC'] [parameters: (7, 7)] (Background on this error at: http://sqlalche.me/e/e3q8) 127.0.0.1 - - [16/Feb/2019 10:43:00] "GET / HTTP/1.1" 500 -

  • #63 Miguel Grinberg said 2019-02-16T19:39:21Z

    @JOHN: the stack trace is long, but you have to identify what the error is. In your case, the error message is "no such column: post.timestamp". It means that your database does not have the timestamp column defined for the posts table.

  • #64 Danyel said 2019-03-05T09:58:50Z

    Hi Miguel! When I try to explore last page of blog post's I get:

    File "...\blog\app\templates_post.html", line 3, in top-level template code jinja2.exceptions.UndefinedError: 'None' has no attribute 'avatar' 127.0.0.1 - - [05/Mar/2019 12:46:34] "GET /explore?page=4 HTTP/1.1" 500 -

    Is it right to fix it something like this(to pass "None"):

    {% if post.author %} ... {% endif %}

    or is better way?

    Best regards, Danyel

  • #65 Miguel Grinberg said 2019-03-05T10:11:24Z

    @Danyel: yes, you can do that, but the problem is really that your database has an inconsistency, you have a post that does not have an author set.

  • #66 Doug Leister said 2019-04-19T17:33:06Z

    Miguel,

    Just wanted to say thank you for putting this together. Its been a huge help in helping me to learn about web programming, Flask, SqlAlchemy etc. Even though its a year since its come out, its still getting plenty of use and is a great resource. Not doing a microblog, but instead am adapting it for a project I'm working on.

    Thanks, Doug

  • #67 Collins said 2019-04-21T14:16:56Z

    This seems awesome, however, I think there is a better way of having a single place eg a function which can do pagination for all views, this is a lot of repetition, in that every time you need to paginate you have to query and call .paginate passing the page, limit, etc. Thanks

  • #68 Miguel Grinberg said 2019-04-21T20:20:19Z

    @Collins: I agree. In fact I have shown at a PyCon talk a few years back how to implement the entire pagination logic in a decorator that you can add to a view function.

  • #69 Emircan K said 2019-05-24T15:53:23Z

    Hello Mr. Miguel. I would really like to thank you for providing us aspiring developers with such an excellent guide! I have a minor question. I realized that when I navigate through the site, everything seems to be working fine, except when I navigate to homepage either via the link at the top of the page or by entering the URL by hand, there is a slight delay in the process of page being loaded. And The post requests on index page give a 302 status code. I am not sure if the long loading time is related to the Post requests since simply by trying to navigate to homepage and not post anything, it still takes more than a couple of seconds. I Would really appreciate if you knew what caused the delay in the loading time and shared it with us! Thanks.

  • #70 Miguel Grinberg said 2019-05-24T18:38:35Z

    @Emircan: The post requests returning 302 is on purpose, this is explained earlier in the tutorial, it's the post/redirect/get pattern that prevents double form submissions. The delay is probably external to the application. Are you running the server on a different or same computer? If different, network latencies are going to affect timing, specially if you are on wi-fi.

  • #71 Emircan K said 2019-05-27T15:03:02Z

    @Miguel Grinberg, I do run the server on the same computer and also I am connected via a cable, although recently I have realized the delay comes and goes randomly, that makes it certain that it has to do something with my machine. It was just a minor thing that I looked up but could not find any explanation so wanted to ask you. Thanks for taking your time and responding to us people who have questions here so quickly for such a long time! I hope the best for you. Cannot thank you enough for the help you provided!

  • #72 Borja said 2019-06-17T06:11:57Z

    Hola Miguel,

    Thank you for your help! You are the Flask Master! One question, I have done something similar until this point but now I do not want to paginate. My main route ('/') display a table with columns, so, instead of paginate I would like to load more rows when the user scroll down. Do you have any recommendations? Until now, what I did is using javascript to check the position and then, also with javascript add the new rows but it is a little bit messy. So, I would like to now if there is some plugin or you have some recommendations to do it in a more clean way. Thank you very much.

    Borja

  • #73 Miguel Grinberg said 2019-06-17T18:46:23Z

    @Borja: you can use any of the infinite scroll plugins that are available for the browser. Unfortunately this cannot be done from the Python side.

  • #74 mc said 2019-07-06T20:10:26Z

    Thanks Miguel for this tutorial! Great content and methodology! I'm learning a lot!

  • #75 Juan Manuel Martin said 2019-07-13T16:21:27Z

    Hi Miguel, is there a reason not to instead of doing this:

    @app.route('/explore') @login_required def explore(): page = request.args.get('page', 1, type=int)

    do this:

    @app.route('/explore//') @login_required def explore(page): ......

    and on explore link:

    Explore

Leave a Comment