In this blog, you will learn how to use Flask-Admin, a Flask extension for creating admin interfaces, to manage your database models and users in your web application. You will also learn how to customize the admin interface and add user authentication and authorization features.
1. Introduction
Flask is a popular web framework for Python that allows you to create web applications quickly and easily. However, Flask does not provide a built-in way to create an admin interface for your web application, which is often needed to manage your database models and users.
Fortunately, there is a Flask extension called Flask-Admin that can help you with that. Flask-Admin is a library that lets you create an admin interface for your web application with minimal code and configuration. You can use Flask-Admin to perform common tasks such as creating, updating, deleting, and searching your database models and users. You can also customize the look and feel of your admin interface and add features such as user authentication and authorization.
In this tutorial, you will learn how to use Flask-Admin to create an admin interface for your web application. You will also learn how to customize the admin interface and add user authentication and authorization features. By the end of this tutorial, you will have a fully functional web application with an admin interface.
To follow this tutorial, you will need:
- Python 3.6 or higher installed on your system
- A basic understanding of Flask and how to create web applications with it
- A basic understanding of SQLAlchemy and how to use it to interact with databases
- A text editor or IDE of your choice
Are you ready to create an admin interface for your web application with Flask-Admin? Let’s get started!
2. Setting Up the Project
In this section, you will set up the project for your web application and install the required dependencies. You will also create a basic Flask app and run it on your local server.
To set up the project, you will need to do the following steps:
- Create a new folder for your project and navigate to it in your terminal or command prompt.
- Create a virtual environment for your project and activate it. A virtual environment is a way to isolate your project’s dependencies from other projects on your system. You can use the venv module to create and manage virtual environments in Python.
- Install Flask and Flask-Admin using the pip package manager. Flask is the web framework that you will use to create your web application. Flask-Admin is the extension that you will use to create your admin interface.
- Create a file called app.py in your project folder and write some code to create a basic Flask app. You will also import Flask-Admin and create an instance of it.
- Run your app on your local server and check if it works.
Let’s go through each step in detail.
First, create a new folder for your project and navigate to it in your terminal or command prompt. You can name the folder anything you like, but for this tutorial, we will call it flask_admin_demo. To create and navigate to the folder, you can use the following commands:
mkdir flask_admin_demo
cd flask_admin_demo
Next, create a virtual environment for your project and activate it. A virtual environment is a way to isolate your project’s dependencies from other projects on your system. You can use the venv module to create and manage virtual environments in Python. To create a virtual environment called venv in your project folder, you can use the following command:
python -m venv venv
This will create a folder called venv in your project folder that contains the Python interpreter and the pip package manager for your virtual environment. To activate the virtual environment, you need to run a script that depends on your operating system. For Windows, you can use the following command:
venv\Scripts\activate
For Linux or Mac, you can use the following command:
source venv/bin/activate
You will see a (venv) prefix in your terminal or command prompt that indicates that your virtual environment is activated. You can deactivate the virtual environment at any time by typing deactivate.
Next, install Flask and Flask-Admin using the pip package manager. Flask is the web framework that you will use to create your web application. Flask-Admin is the extension that you will use to create your admin interface. To install both packages, you can use the following command:
pip install flask flask-admin
This will download and install the latest versions of Flask and Flask-Admin and their dependencies in your virtual environment. You can check the installed packages and their versions by using the following command:
pip list
Next, create a file called app.py in your project folder and write some code to create a basic Flask app. You will also import Flask-Admin and create an instance of it. You can use any text editor or IDE of your choice to write the code. For this tutorial, we will use the Visual Studio Code editor. To create the file, you can use the following command:
code app.py
This will open the file in the editor. You can then write the following code in the file:
# Import Flask and Flask-Admin
from flask import Flask
from flask_admin import Admin
# Create a Flask app
app = Flask(__name__)
# Create an Admin instance and pass the app as an argument
admin = Admin(app)
# Run the app on the local server
if __name__ == '__main__':
app.run(debug=True)
This code does the following:
- It imports the Flask and Flask-Admin modules.
- It creates a Flask app object and assigns it to the variable app.
- It creates an Admin object and passes the app object as an argument. This will register the admin interface with the app.
- It runs the app on the local server with the debug mode on. The debug mode allows you to see the errors and changes in your app without restarting the server.
Finally, run your app on your local server and check if it works. To run the app, you can use the following command:
python app.py
This will start the server and display the following output:
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
You can then open your web browser and go to the URL http://127.0.0.1:5000/. You will see a blank page with the text “Hello World!” This is the default response of the Flask app. You can also go to the URL http://127.0.0.1:5000/admin. You will see the admin interface with the title “Home – Flask-Admin”. This is the default view of the Flask-Admin extension. You can click on the “Home” link to go back to the main page of your app.
Congratulations! You have successfully set up the project for your web application and installed the required dependencies. You have also created a basic Flask app and run it on your local server. You have also imported Flask-Admin and created an instance of it. In the next section, you will learn how to create database models for your web application.
3. Creating Database Models
In this section, you will create database models for your web application. Database models are classes that represent the tables and columns in your database. They allow you to define the structure and relationships of your data and interact with it using Python code.
To create database models, you will need to do the following steps:
- Install SQLAlchemy and Flask-SQLAlchemy using pip. SQLAlchemy is an ORM (Object Relational Mapper) that provides a high-level abstraction for working with databases. Flask-SQLAlchemy is a Flask extension that integrates SQLAlchemy with Flask and adds some convenience features.
- Create a file called models.py in your project folder and import the necessary modules. You will also create a database URI (Uniform Resource Identifier) that specifies the location and name of your database file. You will use SQLite as your database engine, which is a lightweight and easy-to-use database that stores data in a single file.
- Create a database object and a database session object. The database object represents the connection to your database and provides methods for creating, dropping, and querying tables. The database session object represents a collection of operations that can be committed or rolled back as a unit. You will use the database session object to add, update, delete, and query your data.
- Create two database models: Post and User. The Post model will represent a blog post with a title, content, and author. The User model will represent a user with a username, email, and password. You will also define a one-to-many relationship between the User and Post models, meaning that one user can have many posts, but each post can only have one user.
- Create the database tables by using the create_all() method of the database object. This will create the tables and columns in your database file according to your database models.
Let’s go through each step in detail.
First, install SQLAlchemy and Flask-SQLAlchemy using pip. SQLAlchemy is an ORM (Object Relational Mapper) that provides a high-level abstraction for working with databases. Flask-SQLAlchemy is a Flask extension that integrates SQLAlchemy with Flask and adds some convenience features. To install both packages, you can use the following command:
pip install sqlalchemy flask-sqlalchemy
This will download and install the latest versions of SQLAlchemy and Flask-SQLAlchemy and their dependencies in your virtual environment. You can check the installed packages and their versions by using the following command:
pip list
Next, create a file called models.py in your project folder and import the necessary modules. You will also create a database URI (Uniform Resource Identifier) that specifies the location and name of your database file. You will use SQLite as your database engine, which is a lightweight and easy-to-use database that stores data in a single file. To create the file, you can use the following command:
code models.py
This will open the file in the editor. You can then write the following code in the file:
# Import SQLAlchemy and Flask-SQLAlchemy
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from flask_sqlalchemy import SQLAlchemy
# Create a database URI
DATABASE_URI = 'sqlite:///flask_admin_demo.db'
# Create a database object
db = SQLAlchemy()
# Create a database session object
session = db.session
This code does the following:
- It imports the SQLAlchemy and Flask-SQLAlchemy modules. It also imports some specific classes and functions from SQLAlchemy, such as Column, Integer, String, ForeignKey, and relationship. These are used to define the attributes and relationships of your database models.
- It creates a database URI that specifies the location and name of your database file. The format of the database URI is dialect+driver://username:password@host:port/database. For SQLite, you only need to specify the dialect (sqlite) and the database name (flask_admin_demo.db). The database file will be created in your project folder.
- It creates a database object and assigns it to the variable db. The database object represents the connection to your database and provides methods for creating, dropping, and querying tables.
- It creates a database session object and assigns it to the variable session. The database session object represents a collection of operations that can be committed or rolled back as a unit. You will use the database session object to add, update, delete, and query your data.
Next, create two database models: Post and User. The Post model will represent a blog post with a title, content, and author. The User model will represent a user with a username, email, and password. You will also define a one-to-many relationship between the User and Post models, meaning that one user can have many posts, but each post can only have one user. To create the database models, you can write the following code in the same file:
# Create a Post model
class Post(db.Model):
# Define the table name
__tablename__ = 'posts'
# Define the table columns
id = Column(Integer, primary_key=True)
title = Column(String(100), nullable=False)
content = Column(String(1000), nullable=False)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
# Define the relationship to the User model
user = relationship('User', backref='posts')
# Define a string representation of the model
def __repr__(self):
return f''
# Create a User model
class User(db.Model):
# Define the table name
__tablename__ = 'users'
# Define the table columns
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True, nullable=False)
email = Column(String(50), unique=True, nullable=False)
password = Column(String(50), nullable=False)
# Define a string representation of the model
def __repr__(self):
return f''
This code does the following:
- It creates a Post model and inherits from the db.Model class. This tells SQLAlchemy that the Post class is a database model.
- It defines the table name for the Post model as posts. This tells SQLAlchemy what name to use for the table in the database.
- It defines the table columns for the Post model as id, title, content, and user_id. Each column is an instance of the Column class, which takes the data type and some optional arguments as parameters. The id column is the primary key, which uniquely identifies each row in the table. The title and content columns are strings that cannot be null. The user_id column is an integer that references the id column of the User model. This creates a foreign key constraint, which ensures that the user_id value in the Post table matches the id value in the User table.
- It defines the relationship to the User model as user. This is an instance of the relationship function, which takes the name of the related model and an optional backref argument as parameters. The backref argument specifies the name of the attribute that will be added to the related model to access the current model. In this case, the User model will have an attribute called posts that will return a list of all the posts associated with that user.
- It defines a string representation of the Post model as . This tells SQLAlchemy how to display the Post object when printed or logged.
- It creates a User model and inherits from the db.Model class. This tells SQLAlchemy that the User class is a database model.
- It defines the table name for the User model as users. This tells SQLAlchemy what name to use for the table in the database.
- It defines the table columns for the User model as id, username, email, and password. Each column is an instance of the Column class, which takes the data type and some optional arguments as parameters. The id column is the primary key, which uniquely identifies each row in the table. The username and email columns are strings that are unique and cannot be null. The password column is a string that cannot be null.
- It defines a string representation of the User model as . This tells SQLAlchemy how to display the User object when printed or logged.
Finally, create the database tables by using the create_all() method of the database object. This will create the tables and columns in your database file according to your database models. To create the database tables, you can write the following code in the same file:
# Create the database tables
db.create_all()
This will execute the SQL commands to create the tables and columns in your database file. You can check the database file by using a SQLite
4. Configuring Flask-Admin
In this section, you will configure Flask-Admin to display and manage your database models in the admin interface. You will also customize the appearance and behavior of the admin interface to suit your needs.
To configure Flask-Admin, you will need to do the following steps:
- Import the ModelView class from Flask-Admin. The ModelView class is a base class that provides a default view for your database models. You can inherit from this class and override its attributes and methods to customize the view.
- Create two subclasses of the ModelView class: PostView and UserView. These classes will represent the views for the Post and User models, respectively. You will also specify some attributes and methods to customize the views.
- Add the PostView and UserView instances to the admin object. This will register the views with the admin interface and display them as links on the home page.
- Update the app.py file to import the models and views modules and initialize the database object with the app object. This will ensure that the database and the admin interface are properly connected to the app.
- Restart the app and check the admin interface. You will see the Post and User views on the home page and be able to create, update, delete, and search the database models.
Let’s go through each step in detail.
First, import the ModelView class from Flask-Admin. The ModelView class is a base class that provides a default view for your database models. You can inherit from this class and override its attributes and methods to customize the view. To import the ModelView class, you can write the following code in the models.py file:
# Import the ModelView class from Flask-Admin
from flask_admin.contrib.sqla import ModelView
Next, create two subclasses of the ModelView class: PostView and UserView. These classes will represent the views for the Post and User models, respectively. You will also specify some attributes and methods to customize the views. To create the subclasses, you can write the following code in the same file:
# Create a PostView class
class PostView(ModelView):
# Specify the columns to display in the list view
column_list = ('title', 'content', 'user')
# Specify the column labels
column_labels = dict(title='Title', content='Content', user='Author')
# Specify the column filters
column_filters = ('title', 'user.username')
# Specify the column formatters
column_formatters = dict(content=lambda v, c, m, p: m.content[:50] + '...')
# Specify the column search fields
column_searchable_list = ('title', 'content', User.username)
# Specify the column default sort
column_default_sort = ('title', False)
# Specify the form fields to display in the create and edit views
form_columns = ('title', 'content', 'user')
# Specify the form field validators
form_args = dict(
title=dict(validators=[DataRequired()]),
content=dict(validators=[DataRequired()]),
user=dict(validators=[DataRequired()])
)
# Create a UserView class
class UserView(ModelView):
# Specify the columns to display in the list view
column_list = ('username', 'email', 'password')
# Specify the column labels
column_labels = dict(username='Username', email='Email', password='Password')
# Specify the column filters
column_filters = ('username', 'email')
# Specify the column formatters
column_formatters = dict(password=lambda v, c, m, p: '*****')
# Specify the column search fields
column_searchable_list = ('username', 'email')
# Specify the column default sort
column_default_sort = ('username', True)
# Specify the form fields to display in the create and edit views
form_columns = ('username', 'email', 'password')
# Specify the form field validators
form_args = dict(
username=dict(validators=[DataRequired(), Unique(User.username)]),
email=dict(validators=[DataRequired(), Email(), Unique(User.email)]),
password=dict(validators=[DataRequired(), EqualTo('confirm_password')]),
confirm_password=dict(validators=[DataRequired()])
)
# Specify the form field widgets
form_widget_args = dict(
password=dict(widget=PasswordInput()),
confirm_password=dict(widget=PasswordInput())
)
# Override the on_model_change method to hash the password
def on_model_change(self, form, model, is_created):
model.password = generate_password_hash(model.password)
This code does the following:
- It creates a PostView class and inherits from the ModelView class. This tells Flask-Admin that the PostView class is a custom view for the Post model.
- It specifies the columns to display in the list view as title, content, and user. The list view is the default view that shows all the records in the table as a list. The columns are specified as a list of strings that match the attribute names of the model.
- It specifies the column labels as Title, Content, and Author. The column labels are the names that are displayed on the list view and the form view. The column labels are specified as a dictionary that maps the attribute names of the model to the desired labels.
- It specifies the column filters as title and user.username. The column filters are the fields that can be used to filter the records in the list view. The column filters are specified as a list of strings or tuples that match the attribute names of the model or the related model. In this case, the user.username filter refers to the username attribute of the User model that is related to the Post model.
- It specifies the column formatters as a lambda function that truncates the content column to 50 characters and adds an ellipsis. The column formatters are the functions that can be used to format the values of the columns in the list view. The column formatters are specified as a dictionary that maps the attribute names of the model to the desired functions. The functions take four arguments: the view, the context, the model, and the name of the property.
- It specifies the column search fields as title, content, and User.username. The column search fields are the fields that can be used to search the records in the list view. The column search fields are specified as a list of strings that match the attribute names of the model or the related model. In this case, the User.username search field refers to the username attribute of the User model that is related to the Post model.
- It specifies the column default sort as title in descending order. The column default sort is the field and order that are used to sort the records in the list view by default. The column default sort is specified as a string or a tuple that matches the attribute name of the model and a boolean value that indicates the order. True means ascending order and False means descending order.
- It specifies the form fields to display in the create and edit views as title, content, and user. The create and edit views are the views that allow you to create and update the records in the table. The form fields are specified as a list of strings that match the attribute names of the model.
- It specifies the form field validators as DataRequired for all the fields. The form field validators are the functions that can be used to validate the input values of the form fields in the create and edit views. The form field validators are specified as a dictionary that maps the attribute names of the model to the desired validators. The validators are imported from the WTForms library, which is a form handling and validation library for Python. The DataRequired validator checks that the input value is not empty.
- It defines a string representation of the PostView class as . This tells Flask-Admin how to display the PostView object when printed or logged.
- It creates a UserView class and inherits from the ModelView class. This tells Flask-Admin that the UserView class is a custom view for the User model.
- It specifies the columns to display in the list view as username, email, and password. The list view is the default view that shows all the records in the table as a list. The columns are specified as a list of strings that match the attribute names of the model.
- It specifies the column labels as Username, Email, and Password. The column labels are the names that are displayed on the list view and the form view. The column labels are specified as a dictionary that maps the attribute names of the model to the desired labels.
- It specifies the column filters as username and email. The column filters are the fields that can be used to filter the records in the list view. The column filters are specified as a list of strings or tuples that match the attribute names of the model or the related model.
- It specifies the column formatters as a lambda function that replaces the password column with asterisks. The column formatters are the functions that can be used to format the values of the columns in the list view. The column formatters are specified as a
5. Customizing the Admin Interface
In the previous section, you learned how to configure Flask-Admin and register your database models with it. You also learned how to use the built-in views and actions of Flask-Admin to manage your database models and users. However, you may have noticed that the default admin interface is not very appealing or user-friendly. It does not have a custom title, logo, or theme. It also does not have any validation, filters, or search options for your database models and users. In this section, you will learn how to customize the admin interface and make it more attractive and functional.
To customize the admin interface, you will need to do the following steps:
- Change the title, logo, and theme of the admin interface.
- Add validation rules and custom messages for your database models and users.
- Add filters and search options for your database models and users.
- Add custom columns and formatters for your database models and users.
- Add custom actions and buttons for your database models and users.
Let’s go through each step in detail.
5.1. Changing the Title, Logo, and Theme of the Admin Interface
By default, the admin interface has the title “Home – Flask-Admin” and the logo “Flask-Admin”. You can change these to something more relevant and meaningful for your web application. You can also change the theme of the admin interface to make it more visually appealing. Flask-Admin supports several themes based on the Bootstrap framework, such as bootstrap2, bootstrap3, cerulean, cosmo, cyborg, darkly, flatly, journal, lumen, paper, readable, sandstone, simplex, slate, spacelab, superhero, united, and yeti. You can choose any of these themes or create your own custom theme.
To change the title, logo, and theme of the admin interface, you need to pass some arguments to the Admin object when you create it. The arguments are:
- name: The name of the admin interface that will be displayed as the title and the logo.
- template_mode: The theme of the admin interface that will be used for the layout and styling.
- index_view: The view that will be used for the home page of the admin interface. You can use the default AdminIndexView or create your own custom view.
For example, you can change the name of the admin interface to “My Web App”, the theme to “darkly”, and the index view to the default one by using the following code:
# Import Flask and Flask-Admin
from flask import Flask
from flask_admin import Admin
# Create a Flask app
app = Flask(__name__)
# Create an Admin instance and pass the app and some arguments
admin = Admin(app, name="My Web App", template_mode="darkly")
# Run the app on the local server
if __name__ == '__main__':
app.run(debug=True)
This will change the appearance of the admin interface.
You can experiment with different themes and see how they look. You can also create your own custom theme by following the instructions in the Flask-Admin documentation.
6. Adding User Authentication and Authorization
In the previous section, you learned how to customize the admin interface and make it more attractive and functional. However, you may have noticed that the admin interface is accessible to anyone who visits the URL http://127.0.0.1:5000/admin. This is not very secure, as anyone can view and modify your database models and users without your permission. In this section, you will learn how to add user authentication and authorization to your admin interface and restrict access to authorized users only.
To add user authentication and authorization to your admin interface, you will need to do the following steps:
- Create a user model and a role model for your web application.
- Create a user loader function and a role loader function for Flask-Login.
- Create a custom admin view class that inherits from the ModelView class and overrides some methods.
- Create a custom index view class that inherits from the AdminIndexView class and overrides some methods.
- Register your custom admin view class and index view class with the admin interface.
- Add login and logout routes and templates for your web application.
Let’s go through each step in detail.
6.1. Creating a User Model and a Role Model for Your Web Application
To add user authentication and authorization to your web application, you need to create a user model and a role model for your database. A user model is a database model that represents a user of your web application. A role model is a database model that represents a role or a permission level of a user. For example, you can have a role model called Admin that grants full access to the admin interface, and a role model called User that grants limited access to the admin interface.
To create a user model and a role model, you need to use the Flask-Login extension and the PasswordType column type from the SQLAlchemy-Utils library. Flask-Login is a Flask extension that provides user session management for your web application. It allows you to log in and log out users, remember their sessions, and restrict access to certain views. PasswordType is a column type that allows you to store and manage passwords securely in your database. It automatically hashes and verifies passwords using the passlib library.
To install Flask-Login and SQLAlchemy-Utils, you can use the following command:
pip install flask-login sqlalchemy-utils
This will download and install the latest versions of Flask-Login and SQLAlchemy-Utils and their dependencies in your virtual environment. You can check the installed packages and their versions by using the following command:
pip list
Next, you need to import Flask-Login and SQLAlchemy-Utils in your app.py file and initialize them with your app and database objects. You also need to import the relationship and backref functions from SQLAlchemy to create associations between your database models. You can use the following code to do that:
# Import Flask and Flask-Admin
from flask import Flask
from flask_admin import Admin
# Import SQLAlchemy and SQLAlchemy-Utils
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_utils import PasswordType
from sqlalchemy import relationship, backref
# Import Flask-Login
from flask_login import LoginManager, UserMixin, current_user
# Create a Flask app
app = Flask(__name__)
# Create a secret key for the app
app.secret_key = "secret"
# Create a database URI for the app
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
# Create a SQLAlchemy database object
db = SQLAlchemy(app)
# Create a Flask-Login login manager object
login_manager = LoginManager(app)
This code does the following:
- It imports Flask and Flask-Admin modules.
- It imports SQLAlchemy and SQLAlchemy-Utils modules.
- It imports Flask-Login module.
- It creates a Flask app object and assigns it to the variable app.
- It creates a secret key for the app and assigns it to the app’s configuration. The secret key is used to encrypt and decrypt the user sessions and cookies.
- It creates a database URI for the app and assigns it to the app’s configuration. The database URI is a string that specifies the type and location of the database. In this case, we are using a SQLite database file called db.sqlite in the same folder as the app.
- It creates a SQLAlchemy database object and passes the app object as an argument. This will connect the app to the database.
- It creates a Flask-Login login manager object and passes the app object as an argument. This will initialize the Flask-Login extension with the app.
Next, you need to create a user model and a role model for your database. You can use the following code to do that:
# Create a role model
class Role(db.Model):
# Create an id column
id = db.Column(db.Integer, primary_key=True)
# Create a name column
name = db.Column(db.String(50), unique=True)
# Create a __repr__ method
def __repr__(self):
return f""
# Create a user model
class User(db.Model, UserMixin):
# Create an id column
id = db.Column(db.Integer, primary_key=True)
# Create a username column
username = db.Column(db.String(50), unique=True)
# Create a password column
password = db.Column(PasswordType(
schemes=["pbkdf2_sha512", "md5_crypt"],
deprecated=["md5_crypt"]
))
# Create a role_id column
role_id = db.Column(db.Integer, db.ForeignKey("role.id"))
# Create a role relationship
role = relationship("Role", backref=backref("users"))
# Create a __repr__ method
def __repr__(self):
return f""
This code does the following:
- It creates a role model class called Role that inherits from the db.Model class.
- It creates an id column for the role model that is an integer, a primary key, and auto-incremented.
- It creates a name column for the role model that is a string and unique.
- It creates a __repr__ method for the role model that returns a string representation of the role object.
- It creates a user model class called User that inherits from the db.Model and UserMixin classes. The UserMixin class provides some default methods and properties for the user model, such as is_authenticated, is_active, is_anonymous, and get_id.
- It creates an id column for the user model that is an integer, a primary key, and auto-incremented.
- It creates a username column for the user model that is a string and unique.
- It creates a password column for the user model that is a PasswordType column. The PasswordType column takes a list of hashing schemes and a list of deprecated schemes as arguments. The hashing schemes are used to hash and verify the passwords. The deprecated schemes are used to migrate the passwords from old hashes to new hashes. In this case, we are using the pbkdf2_sha512 scheme as the default and the md5_crypt scheme as the deprecated one.
- It creates a role_id column for the user model that is an integer and a foreign key to the role model’s id column.
- It creates a role relationship for the user model that links the user model to the role model using the relationship and backref functions. The relationship function creates a virtual column that allows you to access the related role object from the user object. The backref function creates a virtual column that allows you to access the related user objects from the role object.
- It creates a __repr__ method for the user model that returns a string representation of the user object.
Now that you
7. Conclusion
In this tutorial, you learned how to use Flask-Admin to create an admin interface for your web application. You learned how to set up the project, create database models, configure Flask-Admin, customize the admin interface, and add user authentication and authorization. You also learned how to use some of the features and options of Flask-Admin, such as validation, filters, search, columns, formatters, actions, and buttons. You also learned how to change the title, logo, and theme of the admin interface.
By using Flask-Admin, you can create an admin interface for your web application with minimal code and configuration. You can use Flask-Admin to manage your database models and users in a convenient and secure way. You can also customize the admin interface to suit your needs and preferences. Flask-Admin is a powerful and flexible extension that can help you create and maintain your web application more easily and efficiently.
We hope you enjoyed this tutorial and found it useful. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading and happy coding!