Learn from an instance ---- FLASK-WTF, instance ---- flask-wtf

Source: Internet
Author: User

Learn from an instance ---- FLASK-WTF, instance ---- flask-wtf

This case through the implementation of a registration page writing, to take you to understand the use of FLASK-WTF.

  

The main function is the basic function of the form. The mobile phone number must be 11 digits and cannot be registered through the database. The password must be entered twice and must be the same, and all content cannot be empty. now let's get started!

  

  1. Create a form class.

First, use flask-wtf to ensure that wtf has been installed in your environment. If you are in the python3 environment, we can install it through pip3 install Flask-WTF.

 

After the installation is complete, we will import the data:

      from flask_wtf import Form      from wtforms import StringField, SubmitField, PasswordField, ValidationError      from wtforms.validators import DataRequired, EqualTo, Length      from models import USER

    

Let's understand it step by step !!

    

The first line of code imports the Form class from falsk-wtf, and all the Form classes we create will inherit from this class.

The second line of code imports StringField, SubmitField, PasswordField, and ValidationError from wtforms. What are these things used? I believe that if some HTML users are familiar with the type = "text", type = "submit", type = "password" attributes of <input> elements in HTML forms. the principle is the same.

The third line of code is from wtforms. in validators, DataRequired, pointer to, and Length are imported. DataRequired is used to verify that the form data cannot be empty. pointer to is used to compare whether two codes are equal and Length is used to limit the character Length.

The fourth line of code is the USER class imported into the database model, which is used to query whether the mobile phone number has been registered in the database. If the mobile phone number has been registered, the ValidationError of the second line of code is used to throw a warning.

    

Example:

Class Regist (Form): phone = StringField ("Enter your mobile phone number", validators = [DataRequired (), Length (min = 11, max = 11, message = "11-digit mobile phone number")]) name = StringField ("Enter your username", validators = [DataRequired ()]) password = PasswordField ("enter your password ", validators = [DataRequired ()]) password1 = PasswordField ("repeat the password", validators = [DataRequired (), required to ("password", "password must be the same")]) submit = SubmitField ("submit now") def validate_phone (self, field ): If USER. query. filter_by (phone = field. data). first (): raise ValidationError ("stupid, your mobile phone number has been registered !! ")

Such a single registry class is successfully created !!

  

 Ii. Write logic in view Functions

    First, I listed the Code directly:

# Registration interface @ app. route ("/regist/", methods = ["GET", "POST"]) def regist (): form = Regist () if form. validate_on_submit (): telephone = form. phone. data username = form. name. data password = form. password. data if form. validate_phone (): user = USER (phone = telephone, name = username, password = password) db. session. add (user) db. session. commit () return redirect (url_for ("login") else: return render_template ("regist.html", form = form)

       

We first use form = Regist () to instantiate a form Class Object, followed by a condition statement. validate_on_submit indicates to judge whether the data in the form is empty and whether the maximum length is .... and determine whether the content of the form has been submitted. if yes, it means that we have submitted the form data and performed subsequent operations, if not. this means that we only open this registration page, use return render_template ("regist.html", form = form) to render the template, and pass the instantiated object form as a parameter to the template.

      

The code after submitting the form continues to understand telephone = form. phone. data username = form. name. data password = form. password. the three lines of data code are used to obtain the mobile phone number, user name, and password entered by the user.

      

After obtaining the information, we are making a judgment. call the validate_phone () function of the Registry ticket class. If you forget the content, you can check the above. if this parameter is set to true, it indicates that the mobile phone number is not registered. The subsequent operation will save the data entered by the user to the database.

        user = USER(phone=telephone, name=username, password=password)

      

This Code indicates that the USER table has the phone, name, and password attributes. assign the obtained user data telephone, username, and password to it. session. add (user) db. session. the two lines of code commit () are submitted to the database.

      

Flask-sqlalchemy is used in the database. I will not explain it here, but I will discuss it later. I will post the Code:

lass USER(db.Model):    __tablename__="user"                 id=db.Column(db.Integer,primary_key=True,autoincrement=True)    phone=db.Column(db.String(11),nullable=False)    name=db.Column(db.String(50),nullable=False)    password=db.Column(db.String(100),nullable=False)        

   

 Iii. Use in templates

      Step 3 is also the last step. If your project uses flask-bootstrap, you can use:

        {% import "bootstrap/wtf.html" as wtf %}        <form action="" method="post">              {% block page_content %}                    {{ wtf.quick_form(form) }}              {% endblock %}          </form>

      

Is it convenient for wtf. quick_form (form) to generate a form directly? Of course there is no style. If you want to add a style, you can do this:

          <form method="POST">            {{ form.hidden_tag() }}            {{ form.name.label }} {{ form.name(id='my-text-field') }}            {{ form.submit() }}            </form>

      

Now, it's over. If you understand all this, you can also read its Chinese documents directly.

To be continued ..........

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.