Register and Edit profile in a Flask App

From TRCCompSci - AQA Computer Science
Revision as of 22:43, 26 October 2019 by Admin (talk | contribs) (Create sign up route)
Jump to: navigation, search

Create sign up form

In your 'forms.py' file we need to create a form for the sign-up process. You should have created 'forms.py' when you created your login form. You will also need to import the DateField and SelectField:

from wtforms import StringField, PasswordField, SubmitField, DateField, SelectField

Now for the flaskform, add the following:

class SignUpForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm = PasswordField('Confirm Password', validators=[DataRequired()])
    email = StringField('Email', validators=[])
    DOB = DateField('DOB', format='%Y-%m-%d')
    MF = SelectField('Gender', choices=[('M','Male'), ('F','Female')])
    submit = SubmitField('Sign In')

Create sign up template

My WebApp was created using Visual Studio, and it already created a 'layout' template and then separate 'html' files for each page. If you already have templates set up you should copy one of the 'html' files for a page and edit it to this:

{% extends "layout.html" %}

{% block content %}
    <h1>Sign In</h1>
    <form action="" method="post" novalidate>
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}
        </p>
        <p>
            {{ form.confirm.label }}<br>
            {{ form.confirm(size=32) }}
        </p>
        <p>
            {{ form.email.label }}<br>
            {{ form.email(size=32) }}
        </p>
        <p>
            {{ form.DOB.label }}<br>
            {{ form.DOB(size=32) }}
        </p>
        <p>
            {{ form.MF.label }}<br>
            {{ form.MF() }}
        </p>
        <p>{{ form.submit() }}</p>
    </form>
{% endblock %}

Create sign up route

You will need to add 'SignUpForm' to the current form import. Add the following to create a signup route:

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignUpForm()
    if form.validate_on_submit():
        return redirect('/')
    return render_template('signup.html', title='Sign Up', form=form)

At the moment, the form will reload if it is invalid (remember some fields are set to be required). Currently if the form is valid it redirects to the root of the web app. We need to add additional checks, because the password and the confirm must be the same and we might want to test if the username currently exists.

Insert data into users table