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!
Before we begin, make sure you have Flask installed. If not, you can install it using pip:
pip install flaskNow, create a new directory for your project and navigate to it in your terminal.
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.Open app.py and initialize a Flask app:
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:
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()Now, let's create the registration template:
<!-- 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>Next, let's add the registration route in app.py:
@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')Finally, let's create a success page to confirm the registration:
<!-- 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>You can now run your application using:
flask runVisit http://127.0.0.1:5000/register to test the registration system.
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! š