By using FlaskForm, the form processing can be realized conveniently and quickly.
Explain
- Operating system: Windows 10
- Python version: 3.7x
- Virtual Environment Manager: virtualenv
- Code editor: VS Code
Experimental target
Through the use of flask? WTF form related operations, and complete the new user registration.
install
pip install flask_wtf
Use
First, we create a forms.py file in the todolist directory to define a registered form class for user registration. The sample code is as follows:
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, PasswordField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from models import User class RegisterForm(FlaskForm): username = StringField('User name:', validators=[ DataRequired(), Length(min=6, max=20)]) email = StringField('Mailbox:', validators=[DataRequired(), Email()]) pwd = PasswordField('Password:', validators=[ DataRequired(), Length(min=8, max=120)]) confirm = PasswordField('Confirm password:', validators=[ DataRequired(), EqualTo('pwd')]) submit = SubmitField('Submission') def validate_username(self, username): user = User.query.filter_by(name=username.data).first() if user: raise ValidationError("User nickname already exists.") def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('Mailbox already exists.')
Then modify our routing view todolist\app\views.py. The example code is as follows:
from flask import render_template, redirect, url_for, flash from werkzeug.security import generate_password_hash from app import app, db from forms import RegisterForm from models import User @app.route('/') @app.route('/index') def index(): return render_template('index.html', title="home page") @app.route('/login') def login(): return render_template('login.html', title='Sign in') @app.route('/register', methods=['POST', 'GET']) def register(): form = RegisterForm() if form.validate_on_submit(): username = form.username.data email = form.email.data pwd = form.pwd.data print(username, email, pwd) hash = generate_password_hash(pwd) user = User(name=username, email=email, pwd=pwd) db.session.add(user) db.session.commit() flash('login was successful', category='info') return redirect(url_for('login')) return render_template('register.html', title='register', form=form)
Then, modify todolist\app\templates\base.html and add flash message. The example code is as follows:
<!doctype html> <html lang="en"> <head> {% block head %} <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% block styles %} <!-- Bootstrap CSS --> <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"> {{ bootstrap.load_css() }} {% endblock %} {% if title %} <title>{{title}}</title> {% else %} <title>Wish list</title> {% endif %} {% endblock %} </head> <body> {% include "nav.html" %} <div class="container"> {% for message in get_flashed_messages() %} <div class="alert alert-primary" role="alert"> {{ message }} </div> {% endfor %} <!-- Your page contont --> {% block content %}{% endblock%} </div> {% block scripts %} <!-- Optional JavaScript --> {{ bootstrap.load_js() }} {% endblock %} </body> </html>
Next, improve the registration form in todolist\app\templates\register.html. The example code is as follows:
{% extends 'base.html' %} {% block content %} <h1>Registration page</h1> {% from 'bootstrap/form.html' import render_form %} {{ render_form(form) }} {% endblock %}
Note: because we use the flash_bootstrap plug-in, we can render our form directly through it.
Finally, because the form submission will involve cross domain access CSRF, we need to modify our todolist\config.py file and add a SECRET_KEY field. The example code is as follows:
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SQLALCHEMY_DATABASE_URI = os.environ.get( 'SQLALCHEMY_DATABASE_URI') or 'mysql+pymysql://root:mysql@127.0.0.1:3306/todo' SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = "you will never known it."
At this time, when we run our website, we will enter the registration page http://127.0.0.1:5000/register to register users. If we automatically jump to the login page after registration, it means that the user registration can run normally.