Skip to content

LandRegistry/govuk-frontend-wtf

Repository files navigation

GOV.UK Frontend WTForms Widgets

PyPI version govuk-frontend 5.7.1 Python package

GOV.UK Frontend WTForms is a community tool of the GOV.UK Design System. The Design System team is not responsible for it and cannot support you with using it. Contact the maintainers directly if you need help or you want to request a feature.

This repository contains a set of WTForms widgets used to render WTForm fields using GOV.UK Frontend component styling. This is done using Jinja macros from the GOV.UK Frontend Jinja port of the original GOV.UK Frontend Nunjucks macros. These are kept up-to-date with GOV.UK Frontend releases, are thoroughly tested and produce 100% equivalent markup.

This approach also renders the associated error messages in the appropriate place, shows the error summary component at the top of the page and sets all related accessibility ARIA attributes. Adding the appropriate widget to your existing form Python class, along with far simpler templates, makes it quick and easy to produce fully GOV.UK compliant forms.

If you are looking to build a fully featured Flask app that integrates with GOV.UK Frontend Jinja and GOV.UK Frontend WTForms please use the GOV.UK Frontend Flask template repository to generate your app.

How to use

For more detailed examples please refer to the demo app source code.

After running pip install govuk-frontend-wtf, ensure that you tell Jinja where to load the templates from using the PackageLoader, register WTFormsHelpers, then set an environment variable for SECRET_KEY.

app/__init__.py:

from flask import Flask
from govuk_frontend_wtf.main import WTFormsHelpers
from jinja2 import ChoiceLoader, PackageLoader, PrefixLoader

app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")

app.jinja_loader = ChoiceLoader(
    [
        PackageLoader("app"),
        PrefixLoader(
            {
                "govuk_frontend_jinja": PackageLoader("govuk_frontend_jinja"),
                "govuk_frontend_wtf": PackageLoader("govuk_frontend_wtf"),
            }
        ),
    ]
)

WTFormsHelpers(app)

Import and include the relevant widget on each field in your form class (see table below). Note that in this example widget=GovTextInput() is the only difference relative to a standard Flask-WTF form definition.

app/forms.py:

from flask_wtf import FlaskForm
from govuk_frontend_wtf.wtforms_widgets import GovSubmitInput, GovTextInput
from wtforms import StringField, SubmitField
from wtforms.validators import Email, InputRequired, Length


class ExampleForm(FlaskForm):
    email_address = StringField(
        "Email address",
        widget=GovTextInput(),
        validators=[
            InputRequired(message="Enter an email address"),
            Length(max=256, message="Email address must be 256 characters or fewer"),
            Email(message="Enter an email address in the correct format, like name@example.com"),
        ],
        description="We’ll only use this to send you a receipt",
    )

    submit = SubmitField("Continue", widget=GovSubmitInput())

Create a route to serve your form and template.

app/routes.py:

from flask import redirect, render_template, url_for

from app import app
from app.forms import ExampleForm

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/example-form", methods=["GET", "POST"])
def example():
    form = ExampleForm()
    if form.validate_on_submit():
        return redirect(url_for("index"))
    return render_template("example_form.html", form=form)

Finally, in your template set the page title appropriately if there are any form validation errors, as per GOV.UK Design System guidance. Include the govukErrorSummary() component at the start of the content block. Pass parameters in a dictionary to your form field as per the associated component macro options.

app/templates/example_form.html:

{% extends "base.html" %}

{%- from 'govuk_frontend_jinja/components/error-summary/macro.html' import govukErrorSummary -%}

{% block pageTitle %}{%- if form and form.errors %}Error: {% endif -%}Example form – GOV.UK Frontend WTForms Demo{% endblock %}

{% block content %}
<div class="govuk-grid-row">
    <div class="govuk-grid-column-two-thirds">
        {% if form.errors %}
            {{ govukErrorSummary(wtforms_errors(form)) }}
        {% endif %}

        <h1 class="govuk-heading-xl">Example form</h1>

        <form action="" method="post" novalidate>
            {{ form.csrf_token }}
            
            {{ form.email_address(params={
              'type': 'email',
              'autocomplete': 'email',
              'spellcheck': false
            }) }}
            
            {{ form.submit }}
        </form>
    </div>
</div>
{% endblock %}

Widgets

The available widgets and their corresponding Flask-WTF field types are as follows:

WTForms Field GOV.​UK Widget(s) Notes
BooleanField GovCheckboxInput
DateField GovDateInput
DateTimeField GovDateInput
DecimalField GovTextInput
FileField GovFileInput
MultipleFileField GovFileInput(multiple=True) Note that you need to specify multiple=True when invoking the widget in your form class. Not when you render it in the Jinja template.
FloatField GovTextInput
IntegerField GovTextInput Use params to specify a type if you need to use HTML5 number elements. This will not happen automatically.
PasswordField GovPasswordInput
RadioField GovRadioInput
SelectField GovSelect
SelectMultipleField GovCheckboxesInput Note that this renders checkboxes as <select multiple> elements are frowned upon.
SubmitField GovSubmitInput
StringField GovTextInput
TextAreaField GovTextArea, GovCharacterCount

In order to generate things like email fields using GovTextInput you will need to pass additional params through when rendering it as follows:

{{ form.email_address(params={'type': 'email', 'autocomplete': 'email', 'spellcheck': false}) }}

Running the tests

python3 -m venv venv
source venv/bin/activate
pip install -r tests/requirements.txt
pytest --cov=govuk_frontend_wtf --cov-report=term-missing --cov-branch

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

How to contribute

We welcome contribution from the community. If you want to contribute to this project, please review the code of conduct and contribution guidelines.

Contributors

See the full list of contributors on GitHub

Support

This software is provided "as-is" without warranty. Support is provided on a "best endeavours" basis by the maintainers and open source community.

If you are a civil servant you can # to the UK Government Digital Slack workspace to contact the maintainers listed above and the community of people using this project in the #govuk-design-system channel.

Otherwise, please see the contribution guidelines for how to raise a bug report or feature request.