Skip to content

User Registration

Manish Sah edited this page Sep 21, 2020 · 10 revisions

User Registration

Create a class User which inherits from Sqlalchemy's Model. We will define all the models(Tables) needed for our project in models.py file in blog package

from blog import db


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)

inheriting Model allows sqlalchemy to interact with a table against the class User.

Now, we need to create a table in the database that resembles our class User

open python console by entering python in the terminal and enter the following commands:

  • from blog import db
  • from blog.models import User
  • db.create_all()

db.create_all() will create a table named "user(the name will be in lowercase)" in our database.

Note: for db.create_all() to work, you need to import all the class for which you want to create a table

Creating User forms

Now that we have user model, we need to create a form so that user can sign up. Instead of creating form manually, we will use WTForms to make our task easier

WTforms:

  • WTForms is a flexible forms validation and rendering library for Python web development.
  • It can work with whatever web framework and template engine you choose.
  • It supports data validation, CSRF protection, internationalization (I18N)

Install wtform using pip

pip install wtforms

Now that we have installed wtform, we will create forms.py in our blog package to add all the forms needed for our project

blog/forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, Email, ValidationError
from blog.models import User


class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=2, max=30)])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password', validators=[DataRequired()])
    submit = SubmitField('Sign Up')
Clone this wiki locally