Package: govuk-frontend-wtf
GOV.UK Frontend WTForms WidgetsGOV.UK Frontend WTForms is acommunity toolof theGOV.UK Design System. The Design System team is not responsible for it and cannot support you with using it. Contact themaintainersdirectly if you needhelpor you want to request a feature.This repository contains a set ofWTForms widgetsused to renderWTForm fieldsusingGOV.UK Frontendcomponent styling. This is done using Jinja macros from theGOV.UK Frontend Jinjaport 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 appropriatewidgetto 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 withGOV.UK Frontend JinjaandGOV.UK Frontend WTFormsplease use theGOV.UK Frontend Flasktemplate repository togenerate your app.How to useFor more detailed examples please refer to thedemo app source code.After runningpip install govuk-frontend-wtf, ensure that you tell Jinja where to load the templates from using thePackageLoader, registerWTFormsHelpers, then set an environment variable forSECRET_KEY.app/__init__.py:fromflaskimportFlaskfromgovuk_frontend_wtf.mainimportWTFormsHelpersfromjinja2importChoiceLoader,PackageLoader,PrefixLoaderapp=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 (seetable below). Note that in this examplewidget=GovTextInput()is the only difference relative to a standard Flask-WTF form definition.app/forms.py:fromflask_wtfimportFlaskFormfromgovuk_frontend_wtf.wtforms_widgetsimportGovSubmitInput,GovTextInputfromwtformsimportStringField,SubmitFieldfromwtforms.validatorsimportEmail,InputRequired,LengthclassExampleForm(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:fromflaskimportredirect,render_template,url_forfromappimportappfromapp.formsimportExampleForm@app.route("/")defindex():returnrender_template("index.html")@app.route("/example-form",methods=["GET","POST"])defexample():form=ExampleForm()ifform.validate_on_submit():returnredirect(url_for("index"))returnrender_template("example_form.html",form=form)Finally, in your template set the page title appropriately if there are any form validation errors, as perGOV.UK Design System guidance. Include thegovukErrorSummary()component at the start of thecontentblock. Pass parameters in a dictionary to your form field as per the associatedcomponent 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 %}<divclass="govuk-grid-row"><divclass="govuk-grid-column-two-thirds">{% if form.errors %}
            {{ govukErrorSummary(wtforms_errors(form)) }}
        {% endif %}<h1class="govuk-heading-xl">Example form</h1><formaction=""method="post"novalidate>{{ form.csrf_token }}
            
            {{ form.email_address(params={
              'type': 'email',
              'autocomplete': 'email',
              'spellcheck': false
            }) }}
            
            {{ form.submit }}</form></div></div>{% endblock %}WidgetsThe available widgets and their corresponding Flask-WTF field types are as follows:WTForms FieldGOV.​UK Widget(s)NotesBooleanFieldGovCheckboxInputDateFieldGovDateInputDateTimeFieldGovDateInputDecimalFieldGovTextInputFileFieldGovFileInputMultipleFileFieldGovFileInput(multiple=True)Note that you need to specifymultiple=Truewhen invoking the widget in your form class.Notwhen you render it in the Jinja template.FloatFieldGovTextInputIntegerFieldGovTextInputUseparamsto specify atypeif you need to use HTML5 number elements. This will not happen automatically.PasswordFieldGovPasswordInputRadioFieldGovRadioInputSelectFieldGovSelectSelectMultipleFieldGovCheckboxesInputNote that this renders checkboxes as<select multiple>elements are frowned upon.SubmitFieldGovSubmitInputStringFieldGovTextInputTextAreaFieldGovTextArea, GovCharacterCountIn order to generate things like email fields usingGovTextInputyou will need to pass additional params through when rendering it as follows:{{ form.email_address(params={'type': 'email', 'autocomplete': 'email', 'spellcheck': false}) }}Running the testspython3-mvenvvenvsourcevenv/bin/activate
pipinstall-rtests/requirements.txt
pytest--cov=govuk_frontend_wtf--cov-report=term-missing--cov-branchVersioningWe useSemVerfor versioning. For the versions available, see thetags on this repository.How to contributeWe welcome contribution from the community. If you want to contribute to this project, please review thecode of conductandcontribution guidelines.ContributorsMatt Shaw(Primary maintainer)Andy Mantell(Original author)See the full list ofcontributors on GitHubSupportThis 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 sign up to theUK Government Digital Slackworkspace to contact the maintainers listedaboveand the community of people using this project in the#govuk-design-systemchannel.Otherwise, please see thecontribution guidelinesfor how to raise a bug report or feature request.