One place for hosting & domains

      Forms

      Using Angular 2’s Model-Driven Forms with FormGroup and FormControl

      Introduction

      There are two ways to build forms in Angular 2, namely template-driven and model-driven.

      In this article, we will learn about building model-driven form with validation using the latest forms module, then we will talk about what are the advantages / disadvantages of using model driven form as compared to template-driven form.

      Please refer to How to Build Template-driven Forms in Angular 2 if you would like to learn about template-driven forms.

      View Angular 2 – Model Driven Forms (final) scotch on plnkr

      We will build a form to capture user information based on this interface.

      export interface User {
          name: string; 
          address?: {
              street?: string; 
              postcode?: string;
          }
      }
      

      Here is how the UI will look:

      Angular 2 Model-Driven Forms

      Requirements

      1. Show error message only when:
        • the field is invalid and it’s dirty (the field is touched/edited), or
        • the field is invalid and the form is submitted
      2. Listen and display form changes:
        • when any form values change
        • when form status (form validity) change
      3. Update the initial name field value to ‘Johnwithout trigger form changes.

      Here’s our file structure:

      |- app/
          |- app.component.html
          |- app.component.ts
          |- app.module.ts
          |- main.ts
          |- user.interface.ts
      |- index.html
      |- styles.css
      |- tsconfig.json
      

      In order to use new forms module, we need to npm install @angular/forms npm package and import the reactive forms module in application module.

      1. npm install @angular/forms --save

      Here’s the module for our application app.module.ts:

      app.module.ts

      import { NgModule }      from '@angular/core';
      import { BrowserModule } from '@angular/platform-browser';
      import { FormsModule, ReactiveFormsModule } from '@angular/forms';
      
      import { AppComponent }   from './app.component';
      
      @NgModule({
        imports:      [ BrowserModule, ReactiveFormsModule ],
        declarations: [ AppComponent ],
        bootstrap:    [ AppComponent ]
      })
      
      export class AppModule { }
      

      Let’s move on to create our app component.

      app.component.ts

      import { Component, OnInit } from '@angular/core';
      import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
      
      import { User } from './user.interface';
      
      @Component({
          moduleId: module.id,
          selector: 'my-app',
          templateUrl: 'app.component.html',
      })
      export class AppComponent implements OnInit {
          public myForm: FormGroup; 
          public submitted: boolean; 
          public events: any[] = []; 
      
          constructor(private _fb: FormBuilder) { } 
      
          ngOnInit() {
              
          }
      
          save(model: User, isValid: boolean) {
              this.submitted = true; 
      
              
              
              console.log(model, isValid);
          }
      }
      

      Notes

      1. myForm will be our model driven form. It implements FormGroup interface.
      2. FormBuilder is not a mandatory to building model driven form, but it simplify the syntax, we’ll cover this later.

      This is how our HTML view will look like.

      app.component.html

      <form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)">
      
          
      
          <button type="submit">Submit</button>
      
      </form>
      

      We make sure we bind formGroup to our myForm property in app.component.ts file.

      We’ll handle the form submit (ngSubmit) event in save() function that we defined in our app.component.ts file.

      All set! Let’s implement our model-driven form.

      There are two ways to initialize our form model using model-driven forms in Angular 2.

      Here is the long way to define a form:

      app.component.ts

      ngOnInit() {
      
          
          this.myForm = new FormGroup({
              name: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
              address: new FormGroup({
                  street: new FormControl('', <any>Validators.required),
                  postcode: new FormControl('8000')
              })
          });
      
      }
      

      And here’s the short way (using the form builder):

      app.component.ts

      ngOnInit() {
      
          
          this.myForm = this._fb.group({
                  name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
                  address: this._fb.group({
                      street: ['', <any>Validators.required],
                      postcode: ['']
                  })
              });
      
      }
      

      Both of these options will achieve the same outcome. The latter just has a simpler syntax.

      A form is a type of FormGroup. A FormGroup can contain one FormGroup or FormControl. In our case, myForm is a FormGroup. It contains:

      • A name FormControl
      • An address FormGroup

      The address FormGroup contains 2 form controls:

      We can define a validator for both FormGroup and FormControl. Both accept either a single validator or array of validators.

      Angular 2 comes with a few default validators and we can build our custom validator too. In our case, name has two validators:

      Street has only one required validator.

      Let’s add the user’s name control to our view.

      
      ...
      
      
      <div>
          <label>Name</label>
          <input type="text" formControlName="name">
          <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)">
              Name is required (minimum 5 characters).
          </small>
      </div>
      
      ...
      
      • We saved assigned name to formControlName
      • For validation, since formControl has no export value, we need to read the errors information from our form model.
      • In our case, to check if name field is valid, or if it’s pristine, we’ll need to get the value from myForm controls, e.g., myForm.controls.name.valid. Very long syntax, huh.

      Add an address form group to the view

      Next we’ll add our address form group to the view.

      app.component.html

      ....
      <div formGroupName="address">
          <label>Address</label>
          <input type="text" formControlName="street">
          <small [hidden]="myForm.controls.address.controls.street.valid || (myForm.controls.address.controls.street.pristine && !submitted)">
              street required
          </small>
      </div>
      <div formGroupName="address">
          <label>Postcode</label>
          <input type="text" formControlName="postcode">
      </div>
      ...
      

      We have assigned the group name address to formGroupName. Please note that formGroupName can be used multiple times in the same form. In many examples, you’ll see people do this:

      app.component.html

      ...
          <div formGroupName="address">
              <input formControlName="street">
              <input formControlName="postcode">
          </div>
      ...
      

      This gives us the same results as above:

      app.component.html

      ...
          <div formGroupName="address">
              <input formControlName="street">
          </div>
          <div formGroupName="address">
              <input formControlName="postcode">
          </div>
      ...
      

      This is the same process as the previous section to bind form control.

      Now the syntax gets even longer to retrieve control information. Oh my, myForm.controls.address.controls.street.valid.

      How do we update the form value?

      Now, imagine we need to assign default user’s name John to the field. How can we do that?

      The easiest way is if John is static value:

      app.component.ts

      ...
      this.myForm = this._fb.group({
          name: ['John', [ <any>Validators.required,
          <any>Validators.minLength(5)]]
      });
      ...
      

      What if John is not a static value? We only get the value from API call after we initialize the form model.
      We can do this:-

      app.component.ts

      ...
      (<FormControl>this.myForm.controls['name'])
          .setValue('John', { onlySelf: true });
      ...
      

      The form control exposes a function call setValue which we can call to update our form control value.

      setValue accept optional parameter. In our case, we pass in { onlySelf: true }, mean this change will only affect the validation of this control and not its parent component.

      By default this.myForm.controls[‘name’] is of type AbstractControl. AbstractControl is the base class of FormGroup and FormControl. Therefore, we need to cast it to FormControl in order to utilize control specific function.

      How about updating the whole form model?

      It’s possible! We can do something like this:

      app.component.ts

      ...
          const people = {
                  name: 'Jane',
                  address: {
                      street: 'High street',
                      postcode: '94043'
                  }
              };
      
              (<FormGroup>this.myForm)
                  .setValue(people, { onlySelf: true });
      ...
      

      Now that we’ve build our model-driven form. What are the advantages of using it over template-driven form?

      Unit testable

      Since we have the form model defined in our code, we can unit test it. We won’t discuss detail about testing in this article.

      Listen to form and controls changes

      With reactive forms, we can listen to form or control changes easily. Each form group or form control expose a few events which we can subscribe to (e.g., statusChanges, valuesChanges, etc.).

      Let say we want to do something every time when any form values changed. We can do this:-

      subcribeToFormChanges() {
          
          const myFormValueChanges$ = this.myForm.valueChanges;
      
          
          myFormValueChanges$.subscribe(x => this.events
              .push({ event:STATUS CHANGED, object: x }));
      }
      

      Then call this function in our ngOnInit().

      ngOnInit() {
          
          
          this.subcribeToFormChanges();
      }
      

      Then display all value changes event in our view.

      app.component.html

      ...
      Form changes:
      <div *ngFor="let event of events">
          <pre> {{ event | json }} </pre>
      </div>
      ...
      

      We can imagine more advanced use cases such as changing form validation rules dynamically depends on user selection, etc. Model driven form makes this simpler.

      It depends. If you are not doing unit testing (of course you should!), or you have simple form, go ahead with template-driven forms.

      If you are not doing unit testing or you have simple form, go ahead with template-driven forms.

      If you have advanced use cases, then consider model driven form.

      Something good about template-driven forms as compared to model driven forms, imho:

      1. Template driven form has form.submitted flag in the exported ngForm, while model driven form don’t have that.
      2. Reading form control property in model driven form is not syntax friendly in the view. In our example, the syntax of reading address validity is myForm.controls.address.controls.street.valid while in template driven form we have exported ngModel, the syntax can be shorten to just street.valid. While understand that no exported member is done on purpose in the new design, the long syntax is still eye hurting…
      3. More familiar syntax if you are coming from Angular 1.

      That’s it! Now that you know how to build model-driven form, how about complex and nested model-driven forms? Says, we allow the user to enter multiple addresses now, how can we handle form array and validation? You might be interest in How to Build Nested Model-driven Forms in Angular 2.

      Happy coding.

      How To Use and Validate Web Forms with Flask-WTF


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Web forms, such as text fields and text areas, give users the ability to send data to your application, whether that’s a drop-down or a radio button that the application will use to perform an action, or to send large areas of text to be processed or displayed. For example, in a social media application, you might give users a box where they can add new content to their pages.

      Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language. To render and validate web forms in a safe and flexible way in Flask, you’ll use Flask-WTF, which is a Flask extension that helps you use the WTForms library in your Flask application.

      WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define. For example, if you have a required field, you can ensure data the user submits is provided, or has a certain length.

      WTForms also uses a CSRF token to provide protection from CSRF attacks, which are attacks that allows the attacker to execute unwanted actions on a web application in which the user is authenticated. A successful CSRF attack can force the user to perform state-changing requests like transferring funds to the attacker’s bank account in a banking application, changing the user’s email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

      In this tutorial, you’ll build a small web application that demonstrates how to render and validate web forms using Flask-WTF. The application will have a page for displaying courses that are stored in a Python list, and the index page will have a form for entering the course title, its description, price, availability, and level (beginner, intermediate, or advanced).

      Prerequisites

      Step 1 — Installing Flask and Flask-WTF

      In this step, you’ll install Flask and Flask-WTF, which also installs the WTForms library automatically.

      With your virtual environment activated, use pip to install Flask and Flask-WTF:

      • pip install Flask Flask-WTF

      Once the installation is successfully finished, you’ll see a line similar to the following at the end of the output:

      Output

      Successfully installed Flask-2.0.2 Flask-WTF-1.0.0 Jinja2-3.0.3 MarkupSafe-2.0.1 WTForms-3.0.0 Werkzeug-2.0.2 click-8.0.3 itsdangerous-2.0.1

      As you can see, the WTForms library was also installed as a dependency of the Flask-WTF package. The rest of the packages are Flask dependencies.

      Now that you’ve installed the required Python packages, you’ll set up a web form next.

      Step 2 — Setting up Forms

      In this step, you’ll set up a web form using fields and validators you’ll import from the WTForms library.

      You’ll set up the following fields:

      • Title: A text input field for the course title.
      • Description: A text area field for the course description.
      • Price: An integer field for the price of the course.
      • Level: A radio field for the course level with three choices: Beginner, Intermediate, and Advanced.
      • Available: A checkbox field that indicates whether the course is currently available.

      First, open a new file called forms.py in your flask_app directory. This file will have the forms you’ll need in your application:

      This file will have a class that represents your web form. Add the following imports at the top:

      flask_app/forms.py

      from flask_wtf import FlaskForm
      from wtforms import (StringField, TextAreaField, IntegerField, BooleanField,
                           RadioField)
      from wtforms.validators import InputRequired, Length
      
      

      To build a web form, you will create a subclass of the FlaskForm base class, which you import from the flask_wtf package. You also need to specify the fields you use in your form, which you will import from the wtforms package.

      You import the following fields from the WTForms library:

      In the line from wtforms.validators import InputRequired, Length, you import validators to use on the fields to make sure the user submits valid data. InputRequired is a validator you’ll use to ensure the input is provided, and Length is for validating the length of a string to ensure it has a minimum number of characters, or that it doesn’t exceed a certain length.

      Next, add the following class after the import statements:

      flask_app/forms.py

      
      class CourseForm(FlaskForm):
          title = StringField('Title', validators=[InputRequired(),
                                                   Length(min=10, max=100)])
          description = TextAreaField('Course Description',
                                      validators=[InputRequired(),
                                                  Length(max=200)])
          price = IntegerField('Price', validators=[InputRequired()])
          level = RadioField('Level',
                             choices=['Beginner', 'Intermediate', 'Advanced'],
                             validators=[InputRequired()])
          available = BooleanField('Available', default="checked")
      

      Save and close the file.

      In this CourseForm class, you inherit from the FlaskForm base class you imported earlier. You define a collection of form fields as class variables using the form fields you imported from the WTForms library. When you instantiate a field, the first argument is the field’s label.

      You define the validators for each field by passing a list of the validators you import from the wtforms.validators module. The title field, for example, has the string 'Title' as a label, and two validators:

      • InputRequired: To indicate that the field should not be empty.
      • Length: Takes two arguments; min is set to 10 to make sure that the title is at least 10 characters long, and max is set to 100 to ensure it doesn’t exceed 100 characters.

      The description text area field has an InputRequired validator and a Length validator with the max parameter set to 200, with no value for the min parameter, which means the only requirement is that it doesn’t exceed 200 characters.

      Similarly you define a required integer field for the price of the course called price.

      The level field is a radio field with multiple choices. You define the choices in a Python list and pass it to the choices parameter. You also define the field as required using the InputRequired validator.

      The available field is a check box field. You set a default 'checked' value by passing it to the default parameter. This means the check box will be checked when adding new courses unless the user unchecks it, meaning courses are available by default.

      For more on how to use the WTForms library, see the Crash Course page on the WTForms documentation. See the Fields page for more fields, and the Validators page for more validators to validate form data.

      You’ve configured your web form in a forms.py file. Next, you’ll create a Flask application, import this form, and display its fields on the index page. You’ll also display a list of courses on another page.

      Step 3 — Displaying the Web Form and Courses

      In this step, you’ll create a Flask application, display the web form you created in the previous step on the index page, and also create a list of courses and a page for displaying the courses on it.

      With your programming environment activated and Flask installed, open a file called app.py for editing inside your flask_app directory:

      This file will import the necessary class and helpers from Flask, and the CourseForm from the forms.py file. You’ll build a list of courses, then instantiate the form and pass it to a template file. Add the following code to app.py:

      flask_app/app.py

      from flask import Flask, render_template, redirect, url_for
      from forms import CourseForm
      
      app = Flask(__name__)
      app.config['SECRET_KEY'] = "https://www.digitalocean.com/community/tutorials/your secret key'
      
      
      courses_list = [{
          'title': 'Python 101',
          'description': 'Learn Python basics',
          'price': 34,
          'available': True,
          'level': 'Beginner'
          }]
      
      
      @app.route('/', methods=('GET', 'POST'))
      def index():
          form = CourseForm()
          return render_template('index.html', form=form)
      

      Save and close the file.

      Here you import the following from Flask:

      • The Flask class to create a Flask application instance.
      • The render_template() function to render the index template.
      • The redirect() function to redirect the user to the courses page once a new course is added.
      • The url_for() function for building URLs.

      First you import the CourseForm() class from the forms.py file, then you create a Flask application instance called app.

      You set up a secret key configuration for WTForms to use when generating a CSRF token to secure your web forms. The secret key should be a long random string. See Step 3 of How To Use Web Forms in a Flask Application for more information on how to obtain a secret key.

      Then you create a list of dictionaries called courses_list, which currently has one dictionary with a sample course titled 'Python 101'. Here, you use a Python list as a data store for demonstration purposes. In a real world scenario, you’ll use a database such as SQLite. See How To Use an SQLite Database in a Flask Application to learn how to use a database to store your courses’ data.

      You create a / main route using the app.route() decorator on the index() view function. It accepts both GET and POST HTTP methods in the methods parameter. GET methods are for retrieving data, and POST requests are for sending data to the server, through a web form for example. For more, see How To Use Web Forms in a Flask Application.

      You instantiate the CourseForm() class that represents the web form and save the instance in a variable called form. You then return a call to the render_template() function, passing it a template file called index.html and the form instance.

      To display the web form on the index page, you will first create a base template, which will have all the basic HTML code other templates will also use to avoid code repetition. Then you’ll create the index.html template file you rendered in your index() function. To learn more about templates, see How to Use Templates in a Flask Application.

      Create a templates folder in your flask_app directory where Flask searches for templates, then open a template file called base.html, which will be the base template for other templates:

      • mkdir templates
      • nano templates/base.html

      Add the following code inside the base.html file to create the base template with a navbar and a content block:

      flask_app/templates/base.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
          </style>
      </head>
      <body>
          <nav>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for('index') }}">FlaskApp</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      This base template has all the HTML boilerplate you’ll need to reuse in your other templates. The title block will be replaced to set a title for each page, and the content block will be replaced with the content of each page. The navigation bar has two links, one for the index page where you use the url_for() helper function to link to the index() view function, and the other for an About page if you choose to include one in your application.

      Save and close the file.

      Next, open a template called index.html. This is the template you referenced in the app.py file:

      • nano templates/index.html

      This file will have the web form you passed to the index.html template via the form variable. Add the following code to it:

      flask_app/templates/index.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Add a New Course {% endblock %}</h1>
      
          <form method="POST" action="/">
              {{ form.csrf_token }}
              <p>
                  {{ form.title.label }}
                  {{ form.title(size=20) }}
              </p>
      
              {% if form.title.errors %}
                  <ul class="errors">
                      {% for error in form.title.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.description.label }}
              </p>
              {{ form.description(rows=10, cols=50) }}
      
              {% if form.description.errors %}
                  <ul class="errors">
                      {% for error in form.description.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.price.label }}
                  {{ form.price() }}
              </p>
      
              {% if form.price.errors %}
                  <ul class="errors">
                      {% for error in form.price.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.available() }} {{ form.available.label }}
              </p>
      
              {% if form.available.errors %}
                  <ul class="errors">
                      {% for error in form.available.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.level.label }}
                  {{ form.level() }}
              </p>
      
              {% if form.level.errors %}
                  <ul class="errors">
                      {% for error in form.level.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  <input type="submit" value="Add">
              </p>
          </form>
      
      {% endblock %}
      

      Save and close the file.

      You extend the base template, and set a title in an <h1> tag. Then you render the web form fields inside a <form> tag, setting its method to POST and the action to the / main route, which is the index page. You first render the CSRF token WTForms uses to protect your form from CSRF attacks using the line {{ form.csrf_token }}. This token gets sent to the server with the rest of the form data. Remember to always render this token to secure your forms.

      You render each field using the syntax form.field() and you render its label using the syntax form.field.label. You can pass arguments to the field to control how it is displayed. For example, you set the size of the title input field in {{ form.title(size=20) }}, and you set the numbers of rows and columns for the description text area via the parameters rows and cols the same way you would do normally in HTML. You can use the same method to pass additional HTML attributes to a field such as the class attribute to set a CSS class.

      You check for validation errors using the syntax if form.field.errors. If a field has errors, you loop through them with a for loop and display them in a list below the field.

      While in your flask_app directory with your virtual environment activated, tell Flask about the application (app.py in this case) using the FLASK_APP environment variable. Then set the FLASK_ENV environment variable to development to run the application in development mode and get access to the debugger. For more information about the Flask debugger, see How To Handle Errors in a Flask Application. Use the following commands to do this (on Windows, use set instead of export):

      • export FLASK_APP=app
      • export FLASK_ENV=development

      Next, run the application:

      With the development server running, visit the following URL using your browser:

      http://127.0.0.1:5000/
      

      You’ll see the web form displayed on the index page:

      Index Page

      Try to submit the form without filling in the title. You’ll see an error message informing you that the title is required. Experiment with the form by submitting invalid data (such as a short title less than 10 characters long, or a description over 200 characters long) to see other error messages.

      Filling the form with valid data does nothing so far because you don’t have code that handles form submission. You’ll add the code for that later.

      For now, you need a page to display the courses you have in your list. Later, handling the web form data will add a new course to the list and redirect the user to the courses page to see the new course added to it.

      Leave the development server running and open another terminal window.

      Next, open app.py to add the courses route:

      Add the following route at the end of the file:

      flask_app/app.py

      # ...
      
      @app.route('/courses/')
      def courses():
          return render_template('courses.html', courses_list=courses_list)
      

      Save and close the file.

      This route renders a template called courses.html, passing it the courses_list list.

      Then create the courses.html template to display courses:

      • nano templates/courses.html

      Add the following code to it:

      flask_app/templates/courses.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Courses {% endblock %}</h1>
          <hr>
          {% for course in courses_list %}
              <h2> {{ course['title'] }} </h2>
              <h4> {{ course['description'] }} </h4>
              <p> {{ course['price'] }}$ </p>
              <p><i>({{ course['level'] }})</i></p>
              <p>Availability:
                  {% if course['available'] %}
                      Available
                  {% else %}
                      Not Available
                  {% endif %}</p>
              <hr>
          {% endfor %}
      {% endblock %}
      

      Save and close the file.

      You set a title and loop through the items of the courses_list list. You display the title in an <h2> tag, the description in an <h4> tag, and the price and course level in a <p> tag.
      You check whether the course is available using the condition if course['available']. You display the text “Available” if the course is available, and the text “Not Available” if it’s not available.

      Use your browser to go to the courses page:

      http://127.0.0.1:5000/courses/
      

      You’ll see a page with one course displayed, because you only have one course in your course list so far:

      Courses Page

      Next, open base.html to add a link to the courses page in the navigation bar:

      Edit it to look as follows:

      flask_app/templates/base.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
          </style>
      </head>
      <body>
          <nav>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("index') }}">FlaskApp</a>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("courses') }}">Courses</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Save and close the file.

      Refresh the index page, and you’ll see a new Courses link in the navigation bar.

      You’ve created the pages you need for your application: An index page with a web form for adding new courses and a page for displaying the courses you have in your list.

      To make the application functional, you need to handle the web form data when the user submits it by validating it and adding it to the courses list. You’ll do this next.

      Step 4 — Accessing Form Data

      In this step, you’ll access data the user submits, validate it, and add it to the list of courses.

      Open app.py to add code for handling the web form data inside the index() function:

      Edit the index() function to look as follows:

      flask_app/app.py

      # ...
      @app.route('/', methods=('GET', 'POST'))
      def index():
          form = CourseForm()
          if form.validate_on_submit():
              courses_list.append({'title': form.title.data,
                                   'description': form.description.data,
                                   'price': form.price.data,
                                   'available': form.available.data,
                                   'level': form.level.data
                                   })
              return redirect(url_for('courses'))
          return render_template('index.html', form=form)
      

      Save and close the file.
      Here, you call the validate_on_submit() method on the form object, which checks that the request is a POST request, and runs the validators you configured for each field. If at least one validator returns an error, the condition will be False, and each error will be displayed below the field that caused it.

      If the submitted form data is valid, the condition is True, and the code below the if statement will be executed. You build a course dictionary, and use the append method to add the new course to the courses_list list. You access the value of each field using the syntax form.field.data. After you add the new course dictionary to the courses list, you redirect the user to the Courses page.

      With the development server running, visit the index page:

      http://127.0.0.1:5000/
      

      Fill the form with valid data and submit it. You’ll be redirected to the Courses page, and you’ll see the new course displayed on it.

      Conclusion

      You made a Flask application that has a web form you built using the Flask-WTF extension and the WTForms library. The form has several types of fields to receive data from the user, validate it using special WTForms validators, and add it to a data store.

      If you would like to read more about Flask, check out the other tutorials in the How To Create Web Sites with Flask series.



      Source link

      How To Use Web Forms in a Flask Application


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Web forms, such as text fields and text areas, give users the ability to send data to your application to use it to perform an action, or to send larger areas of text to the application. For example, in a social media application, you might give users a box where they can add new content to their pages. Another example is a login page, where you would give the user a text field to enter their username and a password field to enter their password. The server (your Flask application in this case) uses the data the user submits and either signs them in if the data is valid, or responds with a message like Invalid credentials! to inform the user that the data they submitted is not correct.

      Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language. In this tutorial, you’ll build a small web application that demonstrates how to use web forms. The application will have a page for displaying messages that are stored in a Python list, and a page for adding new messages. You’ll also use message flashing to inform users of an error when they submit invalid data.

      Prerequisites

      Step 1 — Displaying Messages

      In this step, you’ll create a Flask application with an index page for displaying messages that are stored in a list of Python dictionaries.

      First open a new file called app.py for editing:

      Add the following code inside the app.py file to create a Flask server with a single route:

      flask_app/app.py

      from flask import Flask, render_template
      
      app = Flask(__name__)
      
      messages = [{'title': 'Message One',
                   'content': 'Message One Content'},
                  {'title': 'Message Two',
                   'content': 'Message Two Content'}
                  ]
      
      @app.route('/')
      def index():
          return render_template('index.html', messages=messages)
      

      Save and close the file.

      In this file, you first import the Flask class and the render_template() function from the flask package. You then use the Flask class to create a new application instance called app, passing the special __name__ variable, which is needed for Flask to set up some paths behind the scenes. Rendering templates is covered in the tutorial How To Use Templates in a Flask Application.

      You then create a global Python list called messages, which has Python dictionaries inside it. Each dictionary has two keys: title for the title of the message, and content for the message content. This is a simplified example of a data storage method; in a real-world scenario, you’d use a database that permanently saves the data and allows you to manipulate it more efficiently.

      After creating the Python list, you use the @app.route() decorator to create a view function called index(). In it, you return a call to the render_template() function, which indicates to Flask that the route should display an HTML template. You name this template index.html (you’ll create it later), and you pass a variable called messages to it. This variable holds the messages list you previously declared as a value and makes it available to the HTML template. View functions are covered in the tutorial How To Create Your First Web Application Using Flask and Python 3.

      Next, create a templates folder in your flask_app directory where Flask searches for templates, then open a template file called base.html, which will have code that other templates will inherit to avoid code repetition:

      • mkdir templates
      • nano templates/base.html

      Add the following code inside the base.html file to create the base template with a navbar and a content block:

      flask_app/templates/base.html

      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              .message {
                  padding: 10px;
                  margin: 5px;
                  background-color: #f3f3f3
              }
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
      
          </style>
      </head>
      <body>
          <nav>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for('index') }}">FlaskApp</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Save and close the file.

      This base template has all the HTML boilerplate you’ll need to reuse in your other templates. The title block will be replaced to set a title for each page, and the content block will be replaced with the content of each page. The navigation bar has two links, one for the index page where you use the url_for() helper function to link to the index() view function, and the other for an About page if you choose to include one in your application.

      Next, open a template called index.html. This is the template you referenced in the app.py file:

      • nano templates/index.html

      Add the following code to it:

      flask_app/templates/index.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Messages {% endblock %}</h1>
          {% for message in messages %}
              <div class="message">
                  <h3>{{ message['title'] }}</h3>
                  <p>{{ message['content'] }}</p>
              </div>
          {% endfor %}
      {% endblock %}
      

      Save and close the file.

      In this code, you extend the base.html template and replace the contents of the content block. You use an <h1> heading that also serves as a title.

      You use a Jinja for loop in the line {% for message in messages %} to go through each message in the messages list. You use a <div> tag to contain the message’s title and content. You display the title in an <h3> heading and the content in a <p> tag.

      While in your flask_app directory with your virtual environment activated, tell Flask about the application (app.py in this case) using the FLASK_APP environment variable:

      Then set the FLASK_ENV environment variable to development to run the application in development mode and get access to the debugger. For more information about the Flask debugger, see How To Handle Errors in a Flask Application. Use the following commands to do this (on Windows, use set instead of export):

      • export FLASK_ENV=development

      Next, run the application:

      With the development server running, visit the following URL using your browser:

      http://127.0.0.1:5000/
      

      You’ll see the messages in the messages list displayed on the index page:

      Index Page

      Now that you have set up your web application and displayed the messages, you’ll need a way to allow users to add new messages to the index page. This is done through web forms, which you’ll set up in the next step.

      Step 2 — Setting Up Forms

      In this step, you will create a page in your application that allows users to add new messages into the list of messages via a web form.

      Leave the development server running and open a new terminal window.

      First, open your app.py file:

      Add the following route to the end of the file:

      flask_app/app.py

      # ...
      
      @app.route('/create/', methods=('GET', 'POST'))
      def create():
          return render_template('create.html')
      

      Save and close the file.

      This /create route has the methods parameter with the tuple ('GET', 'POST') to accept both GET and POST requests. GET and POST are HTTP methods. By default, only GET requests are accepted, which are used to retrieve data, such as asking the server for an index page or an About page. POST requests are used to submit data to a specific route, which often changes the data on the server.

      In this example, you will ask for the create page using a GET request. The Create page will have a web form with input fields and a Submit button. When a user fills in the web form and clicks the Submit button, a POST request gets sent to the /create route. There you handle the request, validate the submitted data to ensure the user has not submitted an empty form, and add it to the messages list.

      The create() view function currently does only one thing: render a template called create.html when it receives a regular GET request. You will now create this template, then edit the function to handle POST requests in the next step.

      Open a new template file called create.html:

      • nano templates/create.html

      Add the following code to it:

      flask_app/templates/create.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Add a New Message {% endblock %}</h1>
          <form method="post">
              <label for="title">Title</label>
              <br>
              <input type="text" name="title"
                     placeholder="Message title"
                     value="https://www.digitalocean.com/community/tutorials/{{ request.form['title'] }}"></input>
              <br>
      
              <label for="content">Message Content</label>
              <br>
              <textarea name="content"
                        placeholder="Message content"
                        rows="15"
                        cols="60"
                        >{{ request.form['content'] }}</textarea>
              <br>
              <button type="submit">Submit</button>
          </form>
      {% endblock %}
      
      

      Save and close the file.

      In this code, you extend the base.html template and replace the content block with an <h1> heading that serves as a title for the page. In the <form> tag, you set the method attribute to post so the form data gets sent to the server as a POST request.

      In the form, you have a text input field named title; this is the name you’ll use on the application to access the title form data. You give the <input> tag a value of {{ request.form['title'] }}. This is useful to restore the data the user enters so it does not get lost when things go wrong. For example, if the user forgets to fill in the required content text area, a request gets sent to the server and an error message will come back as a response, but the data in the title will not be lost because it will be saved on the request global object, and can be accessed via request.form['title'].

      After the title input field, you add a text area named content with the value {{ request.form['content'] }} for the same reasons mentioned previously.

      Last, you have a Submit button at the end of the form.

      Now, with the development server running, use your browser to navigate to the /create route:

      http://127.0.0.1:5000/create
      

      You will see an “Add a New Message” page with an input field for a message title, a text area for the message’s content, and a Submit button.

      Add a new message

      This form submits a POST request to your create() view function. However, there is no code to handle a POST request in the function yet, so nothing happens after filling in the form and submitting it. In the next step, you’ll handle the incoming POST request when a form is submitted. You’ll check whether the submitted data is valid (not empty), and add the message title and content to the messages list.

      Step 3 — Handling Form Requests

      In this step, you will handle form requests on the application side. You’ll access the form data the user submits via the form you created in the previous step and add it to the list of messages. You’ll also use message flashing to inform users when they submit invalid data. The flash message will only be shown once and will disappear on the next request (if you navigate to another page for example).

      Open the app.py file for editing:

      First, you’ll import the following from the Flask framework:

      • The global request object to access incoming request data that will be submitted via the HTML form you built in the last step.
      • The url_for() function to generate URLs.
      • The flash() function to flash a message when a request is processed (to inform the user that everything went well, or to inform them of an issue if the submitted data is not valid).
      • The redirect() function to redirect the client to a different location.

      Add these imports to the first line in the file:

      flask_app/app.py

      from flask import Flask, render_template, request, url_for, flash, redirect
      
      # ...
      

      The flash() function stores flashed messages in the client’s browser session, which requires setting a secret key. This secret key is used to secure sessions, which allow Flask to remember information from one request to another, such as moving from the new message page to the index page. The user can access the information stored in the session, but cannot modify it unless they have the secret key, so you must never allow anyone to access your secret key. See the Flask documentation for sessions for more information.

      The secret key should be a long random string. You can generate a secret key using the os module with the os.urandom() method, which returns a string of random bytes suitable for cryptographic use. To get a random string using it, open a new terminal and open the Python interactive shell using the following command:

      In the Python interactive shell, import the os module from the standard library and call the os.urandom() method as follows:

      • import os
      • os.urandom(24).hex()

      You’ll get a string similar to the following:

      Output

      'df0331cefc6c2b9a5d0208a726a5d1c0fd37324feba25506'

      You can use the string you get as your secret key.

      To set the secret key, add a SECRET_KEY configuration to your application via the app.config object. Add it directly following the app definition before defining the messages variable:

      flask_app/app.py

      
      # ...
      app = Flask(__name__)
      app.config['SECRET_KEY'] = 'your secret key'
      
      
      messages = [{'title': 'Message One',
                   'content': 'Message One Content'},
                  {'title': 'Message Two',
                   'content': 'Message Two Content'}
                  ]
      # ...
      

      Next, modify the create() view function to look exactly as follows:

      flask_app/app.py

      # ...
      
      @app.route('/create/', methods=('GET', 'POST'))
      def create():
          if request.method == 'POST':
              title = request.form['title']
              content = request.form['content']
      
              if not title:
                  flash('Title is required!')
              elif not content:
                  flash('Content is required!')
              else:
                  messages.append({'title': title, 'content': content})
                  return redirect(url_for('index'))
      
          return render_template('create.html')
      

      In the if statement you ensure that the code following it is only executed when the request is a POST request via the comparison request.method == 'POST'.

      You then extract the submitted title and content from the request.form object that gives you access to the form data in the request. If the title is not provided, the condition if not title would be fulfilled. In that case, you display a message to the user informing them that the title is required using the flash() function. This adds the message to a flashed messages list. You will later display these messages on the page as part of the base.html template. Similarly, if the content is not provided, the condition elif not content will be fulfilled. If so, you add the 'Content is required!' message to the list of flashed messages.

      If the title and the content of the message are properly submitted, you use the line messages.append({'title': title, 'content': content}) to add a new dictionary to the messages list, with the title and content the user provided. Then you use the redirect() function to redirect users to the index page. You use the url_for() function to link to the index page.

      Save and close the file.

      Now, navigate to the /create route using your web browser:

      http://127.0.0.1:5000/create
      

      Fill in the form with a title of your choice and some content. Once you submit the form, you will see the new message listed on the index page.

      Lastly, you’ll display flashed messages and add a link for the “New Message” page to the navigation bar in the base.html template to have easy access to this new page. Open the base template file:

      Edit the file by adding a new <a> tag after the FlaskApp link in the navigation bar inside the <nav> tag. Then add a new for loop directly above the content block to display the flashed messages below the navigation bar. These messages are available in the special get_flashed_messages() function Flask provides. Then add a class attribute called alert to each message and give it some CSS properties inside the <style> tag:

      flask_app/templates/base.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              .message {
                  padding: 10px;
                  margin: 5px;
                  background-color: #f3f3f3
              }
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
      
              .alert {
                  padding: 20px;
                  margin: 5px;
                  color: #970020;
                  background-color: #ffd5de;
              }
      
          </style>
      </head>
      <body>
          <nav>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("index') }}">FlaskApp</a>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("create') }}">Create</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% for message in get_flashed_messages() %}
                  <div class="alert">{{ message }}</div>
              {% endfor %}
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Save and close the file, and then reload https://127.0.0.1:5000 in your browser. The navigation bar will now have a “Create” item that links to the /create route.

      To see how flash messages work, go to the “Create” page, and click the Submit button without filling the two fields. You’ll receive a message that looks like this:

      No title no content flash message

      Go back to the index page and you’ll see that the flashed messages below the navigation bar disappear, even though they are displayed as part of the base template. If they weren’t flashed messages, they would be displayed on the index page too, because it also inherits from the base template.

      Try submitting the form with a title but no content. You’ll see the message “Content is required!”. Click the FlaskApp link in the navigation bar to go back to the index page, then click the Back button to come back to the Create page. You’ll see that the message content is still there. This only works if you click the Back button, because it saves the previous request. Clicking the Create link in the navigation bar will send a new request, which clears the form, and as a result, the flashed message will disappear.

      You now know how to receive user input, how to validate it, and how to add it to a data source.

      Note:
      The messages you add to the messages list will disappear whenever the server is stopped, because Python lists are only saved in memory, to save your messages permanently, you will need to use a database like SQLite. Check out How To Use the sqlite3 Module in Python 3 to learn how to use SQLite with Python.

      Conclusion

      You created a Flask application where users can add messages to a list of messages displayed on the index page. You created a web form, handled the data the user submits via the form, and added it to your messages list. You also used flash messages to inform the user when they submit invalid data.

      If you would like to read more about Flask, check out the other tutorials in the Flask series.



      Source link