Getting Started with Flask: Part 6

By Michael

Today we're going to fix a bug I identified after finishing part 5. If you visit /blog on the site you will run into the error of `jinja2.exceptions.UndefinedError: 'sqlalchemy.util._collections.result object' has no attribute 'user'` if you run the debug server.

This is happening because we are not passing the posts object for the template enginge to loop through. This is a quick fix you can find below.

@app.route('/blog', defaults={"slug":None})
@app.route('/blog/')
def blog(slug):
    if slug is None:
        posts = Post.query.order_by(Post.id.desc()).limit(5)
        return render_template("index.html", posts=posts)
    else:
        post = Post.query.filter_by(slug=slug).first()
        if post is not None:
            return render_template("blog.html", post=post)
        else:
            abort(404)

Other posts by Michael

Getting Started with Flask: Part 5

In our final installment we will set up Apache and WSGI to make our app run in a production environment.

Getting Started with Flask: Part 3

Admin page and authentication!