The Flask Mega-Tutorial Part XI: Facelift

This is the eleventh installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to replace the basic HTML templates with a new set that is based on the Bootstrap user interface framework.

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.

You have been playing with my Microblog application for a while now, so I'm sure you noticed that I haven't spent too much time making it look good, or better said, I haven't spent any time on that. The templates that I put together are pretty basic, with absolutely no custom styling. It was useful for me to concentrate on the actual logic of the application without having the distraction of also writing good looking HTML and CSS.

But I've focused on the backend part of this application for a while now. So in this chapter I'm taking a break from that and will spend some time showing you what can be done to make the application look a bit more polished and professional.

This chapter is going to be a bit different than previous ones, because I'm not going to be as detailed as I normally am with the Python side, which after all, is the main topic of this tutorial. Creating good looking web pages is a vast topic that is largely unrelated to Python web development, but I will discuss some basic guidelines and ideas on how to approach the task, and you will also have the application with the redesigned looks to study and learn from.

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

CSS Frameworks

While we can argue that coding is hard, our pains are nothing compared to those of web designers, who have to write templates that have a nice and consistent look on a list of web browsers. It has gotten better in recent years, but there are still obscure bugs or quirks in some browsers that make the task of designing web pages that look nice everywhere very hard. This is even harder if you also need to target resource and screen limited browsers of tablets and smartphones.

If you, like me, are a developer who just wants to create decent looking web pages, but do not have the time or interest to learn the low level mechanisms to achieve this effectively by writing raw HTML and CSS, then the only practical solution is to use a CSS framework to simplify the task. You will be losing some creative freedom by taking this path, but on the other side, your web pages will look good in all browsers without a lot of effort. A CSS framework provides a collection of high-level CSS classes with pre-made styles for common types of user interface elements. Most of these frameworks also provide JavaScript add-ons for things that cannot be done strictly with HTML and CSS.

Introducing Bootstrap

One of the most popular CSS frameworks is Bootstrap, created by Twitter. If you want to see the kind of pages that can be designed with this framework, the documentation has some examples.

These are some of the benefits of using Bootstrap to style your web pages:

  • Similar look in all major web browsers
  • Handling of desktop, tablet and phone screen sizes
  • Customizable layouts
  • Nicely styled navigation bars, forms, buttons, alerts, popups, etc.

The most direct way to use Bootstrap is to simply import the bootstrap.min.css file in your base template. You can either download a copy of this file and add it to your project, or import it directly from a CDN. Then you can start using the general purpose CSS classes it provides, according to the documentation, which is pretty good. You may also want to import the bootstrap.min.js file containing the framework's JavaScript code, so that you can also use the most advanced features.

Fortunately, there is a Flask extension called Flask-Bootstrap that provides a ready to use base template that has the Bootstrap framework installed. Let's install this extension:

(venv) $ pip install flask-bootstrap

Using Flask-Bootstrap

Flask-Bootstrap needs to be initialized like most other Flask extensions:

app/__init__.py: Flask-Bootstrap instance.

# ...
from flask_bootstrap import Bootstrap

app = Flask(__name__)
# ...
bootstrap = Bootstrap(app)

With the extension initialized, a bootstrap/base.html template becomes available, and can be referenced from application templates with the extends clause.

But as you recall, I'm already using the extends clause with my own base template, which allows me to have the common parts of the page in a single place. My base.html template defined the navigation bar, which included a few links, and also exported a content block . All other templates in my application inherit from the base template and provide the content block with the main content of the page.

So how can I fit the Bootstrap base template? The idea is to use a three-level hierarchy instead of just two. The bootstrap/base.html template provides the basic structure of the page, which includes the Bootstrap framework files. This template exports a few blocks for derived templates such as title, navbar and content (see the complete list of blocks here). I'm going to change my base.html template to derive from bootstrap/base.html and provide implementations for the title, navbar and content blocks. In turn, base.html will export its own app_content block for its derived templates to define the page content.

Below you can see how the base.html looks after I modified it to inherit from the Bootstrap base template. Note that this listing does not include the entire HTML for the navigation bar, but you can see the full implementation on GitHub or by downloading the code for this chapter.

app/templates/base.html: Redesigned base template.

{% extends 'bootstrap/base.html' %}

{% block title %}
    {% if title %}{{ title }} - Microblog{% else %}Welcome to Microblog{% endif %}
{% endblock %}

{% block navbar %}
    <nav class="navbar navbar-default">
        ... navigation bar here (see complete code on GitHub) ...
{% endblock %}

{% block content %}
    <div class="container">
        {% with messages = get_flashed_messages() %}
        {% if messages %}
            {% for message in messages %}
            <div class="alert alert-info" role="alert">{{ message }}</div>
            {% endfor %}
        {% endif %}
        {% endwith %}

        {# application content needs to be provided in the app_content block #}
        {% block app_content %}{% endblock %}
{% endblock %}

Here you can see how I make this template derive from bootstrap/base.html, followed by the three blocks that implement the page title, navigation bar and page content respectively.

The title block needs to define the text that will be used for the page title, with the <title> tags. For this block I simply moved the logic that was inside the <title> tag in the original base template.

The navbar block is an optional block that can be used to define a navigation bar. For this block, I adapted the example in the Bootstrap navigation bar documentation so that it includes a site branding on the left end, followed by the Home and Explore links. I then added the Profile and Login or Logout links aligned with the right border of the page. As I mentioned above, I omitted the HTML in the example above, but you can obtain the full base.html template from the download package for this chapter.

Finally, in the content block I'm defining a top-level container, and inside it I have the logic that renders flashed messages, which are now going to appear styled as Bootstrap alerts. That is followed with a new app_content block that is defined just so that derived templates can define their own content.

The original version of all the page templates defined their content in a block named content. As you saw above, the block named content is used by Flask-Bootstrap, so I renamed my content block as app_content. So all my templates have to be renamed to use app_content as their content block. As an example, here how the modified version of the 404.html template looks like:

app/templates/404.html: Redesigned 404 error template.

{% extends "base.html" %}

{% block app_content %}
    <h1>File Not Found</h1>
    <p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}

Rendering Bootstrap Forms

An area where Flask-Bootstrap does a fantastic job is in rendering of forms. Instead of having to style the form fields one by one, Flask-Bootstrap comes with a macro that accepts a Flask-WTF form object as an argument and renders the complete form using Bootstrap styles.

Below you can see the redesigned register.html template as an example:

app/templates/register.html: User registration template.

{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf %}

{% block app_content %}
    <div class="row">
        <div class="col-md-4">
            {{ wtf.quick_form(form) }}
{% endblock %}

Isn't this great? The import statement near the top works similarly to a Python import on the template side. That adds a wtf.quick_form() macro that in a single line of code renders the complete form, including support for display validation errors, and all styled as appropriate for the Bootstrap framework.

Once again, I'm not going to show you all the changes that I've done for the other forms in the application, but these changes are all made in the code that you can download or inspect on GitHub.

Rendering of Blog Posts

The presentation logic that renders a single blog posts was abstracted into a sub-template called _post.html. All I need to do with this template is make some minor adjustments so that it looks good under Bootstrap.

app/templates/_post.html: Redesigned post sub-template.

    <table class="table table-hover">
            <td width="70px">
                <a href="{{ url_for('user', username=post.author.username) }}">
                    <img src="{{ post.author.avatar(70) }}" />
                <a href="{{ url_for('user', username=post.author.username) }}">
                    {{ post.author.username }}
                {{ post.body }}

Rendering Pagination Links

Pagination links is another area where Bootstrap provides direct support. For this I just went one more time to the Bootstrap documentation and adapted one of their examples. Here is how these look in the index.html page:

app/templates/index.html: Redesigned pagination links.

    <nav aria-label="...">
        <ul class="pager">
            <li class="previous{% if not prev_url %} disabled{% endif %}">
                <a href="{{ prev_url or '#' }}">
                    <span aria-hidden="true">&larr;</span> Newer posts
            <li class="next{% if not next_url %} disabled{% endif %}">
                <a href="{{ next_url or '#' }}">
                    Older posts <span aria-hidden="true">&rarr;</span>

Note that in this implementation, instead of hiding the next or previous link when that direction does not have any more content, I'm applying a disabled state, which will make the link appear grayed out.

I'm not going to show it here, but a similar change needs to be applied to user.html. The download package for this chapter includes these changes.

Before And After

To update your application with these changes, please download the zip file for this chapter and update your templates accordingly.

Below you can see a few before and after pictures to see the transformation. Keep in mind that this change was achieved without changing a single line of application logic!

Login Home Page


  • #76 Miguel Grinberg said 2019-12-05T16:35:54Z

    @Chuck: The bootstrap documentation has snippets of HTML for all the available features. To code a page using this framework you basically use the examples they provide in the documentation as a starting point. That is what I did here. It may look like massive changes when you look at the diff on GitHub, but it is really just switching to the more structured format and the CSS class names required by Bootstrap.

  • #77 Nikhil said 2020-01-24T07:27:10Z

    Keep getting this error: jinja2.exceptions.TemplateAssertionError: block 'content' defined twice

    Any pointers would be helpful

  • #78 Miguel Grinberg said 2020-01-24T12:26:53Z

    @Nikhil: Like the error says, you have defined two blocks with the name "content". This isn't allowed, each block must have a unique name.

  • #79 Roman said 2020-02-20T12:31:58Z

    Hi Miguel!

    Have a really strange problem here, tried even to dowload your zip and replace my whole templates with yours, but still get this error.

    So when I'm trying to navigate to "Explore" I get this error: " File "C:\Users\postn\OneDrive\PY\microblog\app\templates_post.html", line 5, in top-level template code jinja2.exceptions.UndefinedError: 'None' has no attribute 'avatar' - - [20/Feb/2020 14:30:11] "?[35m?[1mGET /explore HTTP/1.1?[0m" 500 - "

    But I get it only on "explore" page. On homepage and profile page posts work well. Could you help with the direction, what can be the issue here? Thanks

  • #80 Miguel Grinberg said 2020-02-20T18:36:47Z

    @Roman: you have at least one post in your database that is not assigned to an author. Check the user_id field in all your posts, and set any that don't have it set.

  • #81 bram said 2020-02-29T14:15:33Z

    Hey Miguel, where can I find the code per chapter? Thanks for your awesome tutorial.

  • #82 Miguel Grinberg said 2020-02-29T17:45:59Z

    @bram: Look for the links near the top of each article.

  • #83 Martin said 2020-03-30T17:31:29Z

    Thank you for the fantastic tutorial. A quick question: is it normal for containers not to work as expected when using flask-bootstrap? For example, I cannot change colors or make more than two columns. Once I load another CSS style sheet directly, the entire look changes completely, including the navigation.

  • #84 Miguel Grinberg said 2020-03-30T18:39:48Z

    @Martin: it really depends on how well or not well this other CSS that you are using integrates with Bootstrap. Normally if you are using Bootstrap you use the layout tools that come with it instead of adding some more CSS.

  • #85 Richard said 2020-04-06T12:10:07Z

    First: Great tutorial! Probably one of the best ones I have ever seen. Congratulations! Second: I have an implementation question: I want to upgrade the flask-bootstrap style. I first played with installing the flask-bootstrap4 package, but this is not what I was aiming for.

    So I want to import the <link rel="stylesheet" .... and the <script ... elements from here: https://getbootstrap.com/docs/4.4/getting-started/introduction/ which are now available in a newer version (4+).

    I think they will be implemented in the of a but we never access that, it comes I guess in the flask-bootstrap package, right? So my approach was to put this in your files to try it but I failed. I altered the

    [base.html] {% extends 'bootstrap/base.html' %}

    {% block scripts %} {% endblock %}

    {% block title %} {% if title %}{{ title }} - SS-Tester{% else %}{{ "error" }}{% endif %} {% endblock %} . . . {% block content %}

    {% endblock %}

    but this just destroys my page, which I guess means it is not working as it is supposed to. Would I for example add other

  • #86 Miguel Grinberg said 2020-04-06T22:37:27Z

    @Richard: the Flask-Bootstrap extension is designed to work with Bootstrap 3, it won't work with Bootstrap 4. You really need to use that Flask-Bootstrap4 fork if you want Bootstrap 4. Or else try Bootstrap-Flask, which is another similar fork.

  • #87 Phakamani said 2020-06-08T12:37:56Z

    Hi , I am a front end developer and i like thrill of using css to style but i have a problem my project wont pick up my css in the static folder

  • #88 Miguel Grinberg said 2020-06-08T22:28:06Z

    @Phakamani: how did you reference the css in your HTML template?

  • #89 Dip said 2020-06-18T12:12:17Z

    As soon as I copy your template codes from github to mine, the website breaks. And I am thrown with this error:

    jinja2.exceptions.TemplateRuntimeError: extended multiple times


  • #90 Miguel Grinberg said 2020-06-19T22:50:39Z

    @Dip: I believe this indicates that a template has multiple extends clauses. Mine do not, so this must be something introduced when you replaced your templates.

  • #91 Brian Faivre said 2020-06-30T07:30:35Z

    Hello Miguel! Thank you for your great work. I have really valued this tutorial and your book on Flask (both editions). Do you have any thoughts on the Flask-Bootstrap project and it's viability moving forward? It appears to be no longer being maintained and still on Bootstrap 3.x. Any suggestions on an alternative or if you have any insight into the Flask-Bootstrap program being updated? Thanks again for all the great work.

  • #92 Miguel Grinberg said 2020-06-30T10:43:47Z

    @Brian: the Bootstrap-Flask project is similar and supports Bootstrap 4.

  • #93 Revanth Talluri said 2020-07-09T17:43:05Z

    Hello Miguel, I have installed the flask-bootstrap using pip. And made changes to my int.py file. But I don't see any bootstrap/base.html template when I run the code and moreover I am not able to run my code. Any chance you can say what I am doing wrong?

    Thanks in advance.

  • #94 Miguel Grinberg said 2020-07-10T08:45:35Z

    @Revanth: I can't if you don't show me your code. Write a question on Stack Overflow with all the relevant code and send me the link.

  • #95 Steve said 2020-07-20T19:54:20Z

    Flask-Bootstrap appears to no longer be maintained as per its last update on PyPi. Flask-BS4 is a fork of Flask-Bootstrap and makes for a viable alternative for anyone working through this tutorial as of July 2020.

  • #96 Miguel Grinberg said 2020-07-20T22:30:02Z

    @Steve: Yes. Bootstrap-Flask is another currently maintained fork.

  • #97 Tom said 2020-08-03T17:22:00Z

    Hi Miguel, thank you once agaig for the blog & answers! Is there any way ti integrate into this freamework Select2 (https://select2.org/)? regards, Tom

  • #98 Miguel Grinberg said 2020-08-03T20:41:13Z

    @Tom: you can write any HTML/CSS/JS that you want, Flask does not really care. So yes, you can incorporate select2 or any other client-side library.

  • #99 Pushkar Sharma said 2020-10-01T13:36:15Z

    This is great

  • #100 Danny said 2020-10-29T04:44:49Z

    Loving this tutorial - easiest-to-follow Python tutorial I've come across. And amazing that you are personally responding to everyone's comments nearly 3 years after starting it. Thank you for your service.

Leave a Comment