Favorites and Admin Management
In this chapter you will learn to implement favorites using a many-to-many relationship and quickly build an admin panel with Flask-Admin.
Many-to-many relationship design
Requirement for favorites: one user can favorite multiple articles, and one article can be favorited by multiple users.
In SQLAlchemy, a many-to-many relationship is implemented through an association table.
Example
File path: add an association table in models.py and modify the Post model
from
datetime
import
datetime
Association table: no need to define it as a model class; create it directly with db.Table
favorites
=
db.
Table
(
'favorites'
,
db.
Column
(
'user_id'
,
db.
Integer
,
db.
ForeignKey
(
'users.id'
)
,
primary_key
=
True
)
,
db.
Column
(
'post_id'
,
db.
Integer
,
db.
ForeignKey
(
'posts.id'
)
,
primary_key
=
True
)
,
db.
Column
(
'created_at'
,
db.
DateTime
,
default
=
datetime
.
utcnow
)
)
class
Post
(
db.
Model
)
:
tablename
=
'posts'
... existing fields unchanged ...
Then run the migration:
(venv) $ flask db migrate -m "新增收藏关联表"
(venv) $ flask db upgrade
Favorite and Unfavorite Views
Example
File path: app/blueprints/user.py (new file)
from
flask
import
Blueprint
,
render_template
,
redirect
,
url_for
,
request
,
flash
from
flask_login
import
login_required
,
current_user
from
app.
models
import
Post
,
db
,
favorites
user_bp
=
Blueprint
(
'user'
,
name
)
@
user_bp.
route
(
"/favorite/int:post_id"
,
methods
=
[
'POST'
]
)
@
login_required
def
toggle_favorite
(
post_id
)
:
"""Toggle favorite status"""
post
=
Post.
query
.
get_or_404
(
post_id
)
Check whether it is already favorited: query the association table for this user-article combination
is_faved
=
db.
session
.
query
(
favorites
)
.
filter
(
favorites.
c
.
user_id
==
current_user.
id
,
favorites.
c
.
post_id
==
post.
id
)
.
first
(
)
is
not
None
if
is_faved:
Remove from favorites
db.
session
.
execute
(
favorites.
delete
(
)
.
where
(
(
favorites.
c
.
user_id
==
current_user.
id
)
&
(
favorites.
c
.
post_id
==
post.
id
)
)
)
db.
session
.
commit
(
)
flash
(
f
'Unfavorited "{post.title}"'
,
'info'
)
else
:
Add to favorites
db.
session
.
execute
(
favorites.
insert
(
)
.
values
(
user_id
=
current_user.
id
,
post_id
=
post.
id
)
)
db.
session
.
commit
(
)
flash
(
f
'Favorited "{post.title}"'
,
'success'
)
return
redirect
(
request.
referrer
or
url_for
(
'main.index'
)
)
@
user_bp.
route
(
"/favorites"
)
@
login_required
def
favorites_list
(
)
:
"""Current user's favorites list"""
Query the articles favorited by the user through the association table
faved_posts
=
Post.
query
.
join
(
favorites
,
(
favorites.
c
.
post_id
==
Post.
id
)
)
.
filter
(
favorites.
c
.
user_id
==
current_user.
id
)
.
order_by
(
favorites.
c
.
created_at
.
desc
(
)
)
.
all
(
)
return
render_template
(
'favorites.html'
,
posts
=
faved_posts
)
Register the Blueprint in app.py
Example
from
app.
blueprints
.
user
import
user_bp
app.
register_blueprint
(
user_bp
)
Add a favorite button to the detail and list pages
Example
{% if current_user.is_authenticated %}
{% endif %}
Favorite actions use a POST request (form submission), not a GET link. GET requests should not have side effects (modifying the database); this is a fundamental principle of web development.
Flask-Admin — Admin Management
Flask-Admin is an extension in the Flask ecosystem comparable to Django Admin.
Once configured, you can manage article and category data in the browser.
(venv) $ pip install flask-admin
Example
File path: app.py or create a new admin_setup.py
from
flask_admin
import
Admin
from
flask_admin.
contrib
.
sqla
import
ModelView
from
app.
models
import
Post
,
Category
,
User
Custom ModelView: control which fields are displayed in the admin panel
class
PostAdmin
(
ModelView
)
:
column_list
=
[
'title'
,
'category'
,
'created_at'
,
'updated_at'
]
column_searchable_list
=
[
'title'
,
'summary'
]
column_filters
=
[
'category'
,
'created_at'
]
form_columns
=
[
'title'
,
'slug'
,
'summary'
,
'content'
,
'category'
]
class
CategoryAdmin
(
ModelView
)
:
column_list
=
[
'name'
,
'slug'
]
form_columns
=
[
'name'
,
'slug'
]
Create an Admin instance
admin
=
Admin
(
app
,
name
=
'RUNOOB Blog Admin'
,
template_mode
=
'bootstrap4'
)
admin.
add_view
(
PostAdmin
(
Post
,
db.
session
,
name
=
'Article'
)
)
admin.
add_view
(
CategoryAdmin
(
Category
,
db.
session
,
name
=
'Category'
)
)
admin.
add_view
(
ModelView
(
User
,
db.
session
,
name
=
'User'
)
)
Start the server and visit /adminto enter the admin management interface.
Flask-Admin vs Django Admin
| Feature | Flask-Admin | Django Admin |
|---|---|---|
| Integration methods | Third-party extension, requires pip install | Built into django.contrib.admin |
| Register models | admin.add_view(ModelView(Model, session)) | admin.site.register(Model) |
| List fields | column_list | list_display |
| Search | column_searchable_list | search_fields |
| Filtering | column_filters | list_filter |
| Requires authentication | Not built in (must manually add @login_required) | Built-in admin permissions |
Flask-Admin is accessible without login by default; you need to combine it with Flask-Login for access control. One simple way is to add
@login_required, or override ModelView'sis_accessiblemethod to check admin permissions.
Chapter Summary
In this chapter you implemented two important features: using a db.Table association table + db.session.execute operations to implement the many-to-many relationship for favorites, and using Flask-Admin to quickly build an admin management system.
Now the blog's interactive features (users, favorites) and management features (admin panel) are complete.