Flask Tutorials: User Registration šŸš€

beginner
7 min

Flask Tutorials: User Registration šŸš€

Welcome to our Flask User Registration tutorial! In this lesson, we'll guide you through creating a user registration system using Flask, a powerful Python web framework. By the end, you'll have a solid understanding of how to build secure and user-friendly registration forms. Let's dive in!

Getting Started šŸ’”

Before we begin, make sure you have Flask installed. If not, you can install it using pip:

bash
pip install flask

Now, create a new directory for your project and navigate to it in your terminal.

Creating the Project Structure šŸ“

flask-user-registration/ ā”œā”€ā”€ app.py ā”œā”€ā”€ templates/ │ ā”œā”€ā”€ base.html │ ā”œā”€ā”€ register.html │ └── success.html ā”œā”€ā”€ static/ │ └── css/ │ └── styles.css └── requirements.txt
  • app.py is our main Python file.
  • templates/ folder contains our HTML templates.
  • static/ folder holds CSS files and other static assets.
  • requirements.txt lists our project dependencies.

Setting Up the Flask Application āœ…

Open app.py and initialize a Flask app:

python
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' app.config['BCRYPT_PASSWORD_COMPILE_METHOD'] = 'sha256' db = SQLAlchemy(app) bcrypt = Bcrypt(app)

Next, let's create our SQLite database and User model:

python
from datetime import datetime class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(120), nullable=False) sign_up_time = db.Column(db.DateTime, default=datetime.utcnow) def set_password(self, password): self.password = bcrypt.generate_password_hash(password).decode('utf-8') def check_password(self, password): return bcrypt.check_password_hash(self.password, password) db.create_all()

Creating the Registration Form šŸŽÆ

Now, let's create the registration template:

html
<!-- templates/register.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> <h1>Register</h1> <form action="{{ url_for('register') }}" method="post"> <label for="username">Username:</label> <input type="text" name="username" required> <br> <label for="password">Password:</label> <input type="password" name="password" required> <br> <button type="submit">Register</button> </form> </body> </html>

Handling Registration Form Submissions šŸ’”

Next, let's add the registration route in app.py:

python
@app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') existing_user = User.query.filter_by(username=username).first() if existing_user: return "Username already taken." new_user = User() new_user.username = username new_user.set_password(password) db.session.add(new_user) db.session.commit() return redirect(url_for('success')) return render_template('register.html')

Creating a Success Page āœ…

Finally, let's create a success page to confirm the registration:

html
<!-- templates/success.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Registration Successful</title> </head> <body> <h1>Registration Successful</h1> <p>You have successfully registered!</p> <a href="{{ url_for('register') }}">Register Again</a> </body> </html>

Running the Application šŸŽÆ

You can now run your application using:

bash
flask run

Visit http://127.0.0.1:5000/register to test the registration system.

Quick Quiz
Question 1 of 1

What is the purpose of the `url_for` function in the registration form?

That's it for our User Registration tutorial! With this knowledge, you can build secure and user-friendly registration systems using Flask. Keep exploring, keep coding! šŸŽ‰