2018-02-13T15:36:23Z

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) ...
    </nav>
{% 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 %}
    </div>
{% 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 %}
    <h1>Register</h1>
    <div class="row">
        <div class="col-md-4">
            {{ wtf.quick_form(form) }}
        </div>
    </div>
{% 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">
        <tr>
            <td width="70px">
                <a href="{{ url_for('user', username=post.author.username) }}">
                    <img src="{{ post.author.avatar(70) }}" />
                </a>
            </td>
            <td>
                <a href="{{ url_for('user', username=post.author.username) }}">
                    {{ post.author.username }}
                </a>
                says:
                <br>
                {{ post.body }}
            </td>
        </tr>
    </table>

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
                </a>
            </li>
            <li class="next{% if not next_url %} disabled{% endif %}">
                <a href="{{ next_url or '#' }}">
                    Older posts <span aria-hidden="true">&rarr;</span>
                </a>
            </li>
        </ul>
    </nav>

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

38 comments

  • #1 Santosh Kumar said 2018-02-14T11:16:00Z

    I am willing not to use bootstrap from pip package and from CDN. What things should I keep in mind apart from wtf.html and base.html?

  • #2 Miguel Grinberg said 2018-02-14T16:37:33Z

    @Santosh: you will need to design your template inheritance structure yourself, pretty much like I was doing up until this chapter.

  • #3 James said 2018-02-15T06:11:02Z

    Is it possible to edit the bootstrap template, like change the background color, or shorten the username and password rectangular boxes that accepts the text, to make them shorter, or even center them in the Sign In page?

  • #4 Miguel Grinberg said 2018-02-15T06:41:57Z

    @James: Absolutely. You are free to change the HTML, and add a CSS file with styles if you want to change how the application looks.

  • #5 Serhiy said 2018-02-15T18:46:12Z

    Hi, Miguel, Thank you for your tutorial next chapter. I have a question - how did you get a Search field at the Microblog bar? I don't have it and I don't see the corresponding code at microblog files.

  • #6 Miguel Grinberg said 2018-02-16T01:12:41Z

    @Serhiy: the search field is in the base.html template, in the navigation bar section.

  • #7 Serhiy said 2018-02-17T00:57:32Z

    Hi, Miguel, No, you don't have it in your code. Please review your zip-file. I have one more question: if you use wtf-forms and try to handle the GET method of Submit control (button) your url will contain csrf_token which is not good I think (as far as I know it's because wtf.quick_form method creates the hidden csrf_token input). Is it possible to prevent displaying it there? If I don't use wtf-forms and build the form with Submit button in html-template then I don't get that effect.

  • #8 Miguel Grinberg said 2018-02-17T01:29:45Z

    @Serhiy: Sorry, what I missed to say is that it is in the navigation bar, but in the commit dedicated to full-text search. I inadvertently generated this screenshot using a future version of the code. Sorry about that, I will update the screenshots to not include the search bar. I'd say don't worry about the search form at this point, all those problems with the CSRF token are addressed in the corresponding chapter.

  • #9 Alexander said 2018-02-24T10:26:27Z

    Hello Miguel! Thanks for the fascinating tutorial! I have a question. How to correctly make inscriptions on forms different from those in the default values? ... \ Lib \ site-packages \ flask_login \ config.py For example, instead of LOGIN_MESSAGE = u'Please log in to access this page. ' Make corrections directly to the file in ... \ Lib \ site-packages \ flask_login \ config.py is this correct? I'm sorry, but I could not find examples myself.

  • #10 Miguel Grinberg said 2018-02-24T18:41:24Z

    Alexander: No, you should never modify the code for your dependencies. Flask-Login does allow you to specify a different login message, see their documentation.

  • #11 Martijn said 2018-03-14T07:18:39Z

    Hey Miguel, First of all thanks a million for the tutorial, saved me a lot of time to learn flask! The basic bootstrap is nice, but I would like to do some more fancy stuff. In other word add other classes for the field or button. I'm now using "class_", e.g. {{ form.username(class_="form-control"}} in the HTML template. It works, but what I would like to know is this the best solution for adding classes and attributes to the HTML tags? Best, Martijn

  • #12 Miguel Grinberg said 2018-03-14T16:03:52Z

    @Martijn: for HTML elements that you generate through Flask-WTF and WTForms your only choice is to add them as arguments to the call that renders them, so what you did is the correct implementation.

  • #13 Mahdi said 2018-03-14T18:29:33Z

    Hi, Miguel, Thank you for your great tutorial. I have a question how we can link css and js files to our pages?

  • #14 Miguel Grinberg said 2018-03-14T21:29:31Z

    @Mahdi: Chapter 14 of this tutorial shows you how you can add a static file to the project. In that chapter it is a file, but the concept is the same for .css and .js files.

  • #15 pythoner said 2018-03-20T09:37:33Z

    @Miguel: I think I'm confused. where are the form fields like username, password1 etc. which lies in the former register.html as below? It seems that they disappeared. <p> {{ form.username.label }}<br> {{ form.username(size=32) }}<br> {% for error in form.username.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </p>

  • #16 Miguel Grinberg said 2018-03-20T17:54:40Z

    @pythoner: Flask-Bootstrap uses the "quick_form()" jinja macro to render the entire form, there is no need to specify each field individually.

  • #17 Alex said 2018-04-06T06:48:12Z

    If I wanted to change the user model to have a list of strings (e.g. "things I like"), what would I have to do to the application to accommodate that? It doesn't seem trivial...

  • #18 Miguel Grinberg said 2018-04-06T21:57:59Z

    @Alex: "things I like" and "blog posts I written" sound pretty similar to me in terms of database schema implementation.

  • #19 kz said 2018-04-07T01:08:27Z

    It's wired. It doesn't like the right top corner screenshot, I find that in this kind of base.html implement, all flashed msg won't show up in login page, all of them will be loaded in the second page.

  • #20 Miguel Grinberg said 2018-04-07T06:18:50Z

    @kz: did you compare your templates against mine on GitHub? If you made a small mistake, that should help you figure out where it is.

  • #21 Abdullah said 2018-04-11T13:06:29Z

    Hello Miguel, Thank you for your great tutorial. How can ı fix size of TextAreaField with wtforms? Actually, How to add style elements of wtforms?

  • #22 Miguel Grinberg said 2018-04-12T02:40:26Z

    @Abdullah: If you are using Flask-WTF directly, you can add any HTML attributes that you want to the render call in the template. I have shown how to do this in the chapter dedicated to web forms. If you want to do the same with Flask-Bootstrap it gets more complicated. You can use CSS selectors to apply your styles, or if you need to actually change the HTML, you have to render the fields independently instead of using the quick_form() macro.

  • #23 Casey said 2018-04-24T01:16:45Z

    Hi Miguel, The tutorial has been extremely helpful; thank you for publishing it. One request as I've been progressing through it on different machines: could you include a requirements.txt file in each of the chapter branches?

  • #24 Miguel Grinberg said 2018-04-24T06:17:00Z

    @Casey: a requirements.txt file is added later in the tutorial, when the topic of deployment starts to come up. If you need to move your project to different machines before that, then you can generate your own requirements file by running "pip freeze > requirements.txt".

  • #25 Sam said 2018-05-03T17:10:28Z

    Hello Miguel, Thanks for the informing tutorial. Is it possible to add an icon to the webpage to be used for tabs and bookmarks?

Leave a Comment