Flask-tastic Admin Panel: A Step-by-Step Guide to Building Your Own
Let us guide you through the process of building a Flask admin panel for your web app and tease the upcoming Forest Admin integration for Flask users.
Flask is a popular, lightweight web framework for Python that makes it easy to build web applications and handle data at the speed of bytes. Now, if you say data, you might want to look into fine-tuning an admin panel to manage it all – byte by byte.
Admin panels are the control centers of web applications, offering a user-friendly dashboard for managing data, user accounts, and various other functionalities. In this article, we'll guide you through the process of building a Flask admin panel for your web app: first from scratch and by generating it with Forest Admin.
How to build a Flask admin panel from scratch
Prerequisites to your Flask admin panel
Before diving into the admin panel creation process, it's crucial to have the right knowledge bytes and toolkits in place.
A. Knowledge requirements
- Python programming language: As Flask is a Python web framework, it's essential to have a solid understanding of the Python language - a must for any Pythonista!
- Basic understanding of Flask web framework: Being familiar with Flask's core concepts, such as routing, views, and templates, will help you stay on track and grasp the material presented in this guide.
B. Technical requirements
- Python installation: Make sure you have a recent version of Python installed on your system. You can download the latest version from the official Python website (https://www.python.org/downloads/).
- Flask and required packages installation: To follow this guide, you'll need to install Flask, Flask-Admin, Flask-SQLAlchemy, and other necessary packages. You can install them using pip, the Python package manager that keeps everything running smooth as a snake.
- Code editor or IDE: A code editor or Integrated Development Environment (IDE) is essential for writing and organizing your code. Popular choices include Visual Studio Code, PyCharm, and Sublime Text - pick your favorite and let the coding magic begin!
Setting up the Flask Application
A. Crafting the Flask Project Structure
Begin by cooking up the perfect project structure for your Flask application. A typical Flask project concoction includes:
- app.py: The main application file where you stir up the Flask app, adding a pinch of initialization and a dash of configuration.
- templates: A directory containing the HTML templates for your application's views, where the visuals come to life.
- static: A directory for static files, such as stylesheets, images, and JavaScript files - the secret ingredients to a well-seasoned app.
- models.py: A file containing the database models for your application, keeping everything in its proper place.
- views.py: A file containing the view functions for your application's routes, the map to navigate your app.
Whip up a new directory for your Flask project, and add the above-mentioned files and folders.
B. Installing the Secret Sauce for your Flask admin panel
With the project structure prepped and ready, it's time to install the secret sauce - the necessary packages. Open a terminal or command prompt, navigate to your project's directory, and run the following command:
pip install flask flask-admin flask-sqlalchemy
This command installs Flask, Flask-Admin, and Flask-SQLAlchemy - the key ingredients for a flavorful admin panel. Flask-Admin is an extension that streamlines the process of crafting admin interfaces for Flask applications, like a master chef. Flask-SQLAlchemy is an ORM (Object Relational Mapper) extension that makes database interaction a piece of cake using Python.
C. Cooking Up the Flask App Configuration
In the app.py file, import the required packages like a shopping list, and fire up the Flask application:
from flask import Flask
from flask_admin import Admin
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'your-database-uri'
db = SQLAlchemy(app)
admin = Admin(app, name='My Admin Panel', template_mode='bootstrap4')
D. Running the Flask application
To run your Flask application, add the following lines at the end of the app.py file:
if __name__ == '__main__':
app.run(debug=True)
Now, you can run your Flask application by executing the app.py file from the terminal or command prompt:
python app.py
Database Setup and Models for your Flask admin panel
A. Choosing a database
Flask-SQLAlchemy is quite the versatile chef, supporting a smorgasbord of databases like SQLite, PostgreSQL, and MySQL. For this guide, we'll be using SQLite, as it's the perfect sous-chef for development purposes with no additional setup required. However, feel free to choose a different database to suit your project's palate and requirements.
B. Configuring the database connection
Time to spice up the 'SQLALCHEMY_DATABASE_URI' configuration in the app.py file to connect to your chosen database. For SQLite, the configuration should look like a gourmet dish:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database_name.db'
Simply replace 'your_database_name' with the desired name for your SQLite database.
Bon appétit!
C. Creating models for the admin panel
In the models.py file, it's time to craft the database models for your admin panel, like an artist sculpting their masterpiece. For this guide, we'll create a Users model, a Roles model, and a Posts model as examples.
Feel free to modify or extend these models to cater to your application's specific tastes and requirements.
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
role_id = db.Column(db.Integer, db.ForeignKey('role.id'), nullable=False)
role = db.relationship('Role', backref=db.backref('users', lazy=True))
class Role(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
content = db.Column(db.Text, nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
author = db.relationship('User', backref=db.backref('posts', lazy=True))
After defining the models, create the database tables by adding the following lines to the app.py file:
from models import User, Role, Post
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
Implementing the Flask-Admin Extension
A. Initializing Flask-Admin
In the app.py file, import the 'ModelView' class from the 'flask_admin.contrib.sqla' package and register the models with the Flask-Admin instance:
from flask_admin.contrib.sqla import ModelView
from models import User, Role, Post
# Register the models with Flask-Admin
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Role, db.session))
admin.add_view(ModelView(Post, db.session))
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
This code adds the User, Role, and Post models to the admin panel, allowing you to manage them through the Flask-Admin interface.
B. Customizing the admin panel
Flask-Admin provides various options for customizing the appearance and behavior of the admin panel. To do this, you can create custom views by subclassing the ModelView
class and overriding its methods or attributes.
Creating custom views
In the views.py file, import the required packages and create custom views for the User, Role, and Post models. For example, you can customize the displayed columns, column labels, or column filters:
from flask_admin.contrib.sqla import ModelView
from models import User, Role, Post
class UserAdmin(ModelView):
column_list = ('username', 'email', 'role')
column_labels = {'username': 'Username', 'email': 'Email Address', 'role': 'Role'}
column_filters = ('username', 'email', 'role.name')
class RoleAdmin(ModelView):
column_list = ('name',)
column_labels = {'name': 'Role Name'}
column_filters = ('name',)
class PostAdmin(ModelView):
column_list = ('title', 'author', 'content')
column_labels = {'title': 'Post Title', 'author': 'Author', 'content': 'Content'}
column_filters = ('title', 'author.username')
Customizing the appearance
You can also customize the appearance of the admin panel by changing the template_mode
attribute when initializing the Flask-Admin instance. For example, you can use Bootstrap 4 for styling:
admin = Admin(app, name='My Admin Panel', template_mode='bootstrap4')
C. Adding custom views to the admin panel
Finally, register the custom views with the Flask-Admin instance in the app.py file:
from views import UserAdmin, RoleAdmin, PostAdmin
admin.add_view(UserAdmin(User, db.session))
admin.add_view(RoleAdmin(Role, db.session))
admin.add_view(PostAdmin(Post, db.session))
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
Now, when you run your Flask application, you should see the customized admin panel at the /admin
URL. You can manage the User, Role, and Post models through the admin panel, and the customizations you made in the custom views should be reflected in the interface.
This covers the first part of building an admin panel with Flask and Flask-Admin. In the next sections, you'll learn about implementing authentication and authorization, integrating the Forest Admin solution, adding additional features, and deploying your admin panel.
Authentication and Authorization for your Flask admin panel
A. Implementing user authentication
To secure your admin panel, you need to implement user authentication. This ensures that only authorized users can access the panel and perform administrative tasks.
Creating login and registration views
In the views.py file, create view functions for user registration and login. Use the 'flask_login' package to manage user sessions:
from flask import render_template, request, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from app import app, db
from models import User
login_manager = LoginManager(app)
login_manager.login_view = 'login'
class UserLogin(UserMixin):
pass
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
# Register a new user and add them to the database
pass
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Authenticate the user and log them in
pass
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
Setting up password hashing and session management
For secure password storage, use a password hashing library like 'werkzeug.security'. Update the registration and login views in the views.py file to hash the passwords and authenticate users:
from werkzeug.security import generate_password_hash, check_password_hash
# Inside the register view function
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = generate_password_hash(request.form['password'])
new_user = User(username=username, email=email, password=password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('login'))
# Inside the login view function
if request.method == 'POST':
user = User.query.filter_by(email=request.form['email']).first()
if user and check_password_hash(user.password, request.form['password']):
login_user(user)
return redirect(url_for('admin.index'))
B. Implementing role-based access control
To restrict access to the admin panel based on user roles, update the custom views in the views.py file to check the user's role before granting access:
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user
class AdminModelView(ModelView):
def is_accessible(self):
return current_user.is_authenticated and current_user.role.name == 'Admin'
class UserAdmin(AdminModelView):
# ... same as before
class RoleAdmin(AdminModelView):
# ... same as before
class PostAdmin(AdminModelView):
# ... same as before
Now, only users with the 'Admin' role can access the admin panel.
Forest Admin to save the day
Building a Flask admin panel is a crucial step in developing a web application, as it provides a centralized platform for managing the application's data, users, and other essential components.
While this guide has outlined the necessary steps and tools to create an effective and secure admin panel using Flask, Flask-Admin, and Flask-SQLAlchemy, there is a way to get it done much faster and easier - by generating a Flask admin panel instead of building it step-by step.
Here is how:
- Get started with Forest Admin by creating a free account. Complete a simple sign-up form to get started immediately.
- In the first step, select an Advanced Setup, unless you want to quickly test Forest Admin with a database. Then all you need to do is to provide a database URI. Read more about Forest Admin Cloud (Instant Setup).
- Select Flask as a data source. Forest Admin is also available for numerous databases and frameworks, such as Django, Laravel, Symfony, Ruby on Rails, Express, PostgreSQL, MySQL, MongoDB, Supabase, and more. It is also possible to add more than one datasource later in setting up a project.
- Follow the step-by-step onboarding instructions, and don't forget to consult the Forest Admin Installation Guide for additional details.
- Congrats, your Flask admin panel is auto-generated! Now, all you need to do is to customize it to your needs. Explore the layout editor, workspaces, smart actions, and invite your team mates!