Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added different Bootswatch usage cases for each Admin instance #2463

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ flask_admin/tests/tmp
dist/*
make.bat
venv
.venv*
*.sublime-*
.coverage
__pycache__
Expand Down
30 changes: 30 additions & 0 deletions examples/multiple-bootswatches/admin/basic_admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from .views import IndexView
from config import FlaskAdminConfig
from models import User, Post, db


class UserModelView(ModelView):
column_editable_list = ['active']
can_edit = False
can_create = False
can_delete = False
can_view_details = False

class PostModelView(ModelView):
column_list = ['id', 'title', 'body', 'author', 'created_at']
column_editable_list = ['title']


admin = Admin(
name='BasicAdmin',
base_template='master.html',
template_mode='bootstrap3',
bootswatch_theme=FlaskAdminConfig.BASIC_ADMIN_BOOTSWATCH_THEME,
index_view=IndexView('Home', endpoint='basicadmin', url='/basicadmin'),
)

admin.add_view(UserModelView(User, db.session, name='Users', endpoint='b/users'))
admin.add_view(PostModelView(Post, db.session, name='Posts', endpoint='b/posts'))

27 changes: 27 additions & 0 deletions examples/multiple-bootswatches/admin/super_admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from .views import IndexView
from config import FlaskAdminConfig
from models import User, Post, db


class UserModelView(ModelView):
column_editable_list = ['active']
can_view_details = True

class PostModelView(ModelView):
column_list = ['id', 'title', 'body', 'author', 'created_at']
column_editable_list = ['title']


admin = Admin(
name='SuperAdmin',
base_template='master.html',
template_mode='bootstrap3',
bootswatch_theme=FlaskAdminConfig.SUPER_ADMIN_BOOTSWATCH_THEME,
index_view=IndexView('Home', endpoint='superadmin', url='/superadmin'),
)

admin.add_view(UserModelView(User, db.session, name='Users', endpoint='s/user'))
admin.add_view(PostModelView(Post, db.session, name='Posts', endpoint='s/posts'))

22 changes: 22 additions & 0 deletions examples/multiple-bootswatches/admin/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{% extends 'master.html' %}

{% block body %}

<h2>This is a {{ admin_view.admin.name }} with the theme <b>"{{ admin_view.admin.bootswatch_theme }}"</b></h2>
<br>
<div class="container">
<ul>
<li>
<a href="{{ url_for('basicadmin.index') }}">
Go to BasicAdmin - {{ basic_admin_bootswatch_theme }}
</a>
</li>
<li>
<a href="{{ url_for('superadmin.index') }}">
Go to SuperAdmin - {{ super_admin_bootswatch_theme}}
</a>
</li>
</ul>
</div>

{% endblock %}
45 changes: 45 additions & 0 deletions examples/multiple-bootswatches/admin/templates/master.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{% extends 'admin/base.html' %}
{% block head %}
{{ super() }}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A=="
crossorigin="anonymous" referrerpolicy="no-referrer" />

{% endblock %}
{% block access_control %}

<ul class="nav navbar-nav navbar-right">
<li class="nav-item">
<a href="javascript:void(0)">
<b>bootswatch_theme:</b> {{ admin_view.admin.bootswatch_theme }}
</a>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="fa fa-rotate"></i>
Change theme
<i class="glyphicon glyphicon-chevron-down small"></i>
</a>
<ul class="dropdown-menu">
<li>
<a href="#">
Darkly
</a>
</li>
<li>
<a href="#" class="btn-primary">
Cosmo
</a>
</li>
</ul>
</li>
</ul>


{% endblock %}
{% block tail %}

<br><br><br><br>

{% endblock %}
10 changes: 10 additions & 0 deletions examples/multiple-bootswatches/admin/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from flask_admin import AdminIndexView, expose
from config import FlaskAdminConfig

class IndexView(AdminIndexView):
@expose('/')
def index(self):
return self.render('index.html',
basic_admin_bootswatch_theme=FlaskAdminConfig.BASIC_ADMIN_BOOTSWATCH_THEME,
super_admin_bootswatch_theme=FlaskAdminConfig.SUPER_ADMIN_BOOTSWATCH_THEME
)
30 changes: 30 additions & 0 deletions examples/multiple-bootswatches/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import sys, os
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from config import MyConfig
from models import db_init
from fake import generate_fake_data
from flask import Flask
from admin.basic_admin import admin as basic_admin
from admin.super_admin import admin as super_admin


app = Flask(__name__)

app.config.from_object(MyConfig)
db_init(app)
generate_fake_data(app)

# Init admin instances

basic_admin.init_app(app)
super_admin.init_app(app)

from bp import bp

app.register_blueprint(bp)


if __name__ == '__main__':
app.run()


22 changes: 22 additions & 0 deletions examples/multiple-bootswatches/bp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from flask import Blueprint
from flask import render_template_string


bp = Blueprint('main', __name__, template_folder='admin/templates')


@bp.route('/')
def index():
return render_template_string('''
<h1>Hello, World!</h1>
<ul>
<li>
<a href="{{ url_for('basicadmin.index') }}">Basic Admin Panel</a>
</li>
<li>
<a href="{{ url_for('superadmin.index') }}">Super Admin Panel</a>
</li>
</ul>
''')


18 changes: 18 additions & 0 deletions examples/multiple-bootswatches/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import os

import sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../flask-admin')))


class MyConfig:
DEBUG = True
SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(16))
SQLALCHEMY_DATABASE_URI = 'sqlite:///sqlite3-multiple-bootswatched.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False


class FlaskAdminConfig:
BASIC_ADMIN_BOOTSWATCH_THEME = 'Cosmo'
SUPER_ADMIN_BOOTSWATCH_THEME = 'United'

36 changes: 36 additions & 0 deletions examples/multiple-bootswatches/fake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from faker import Faker
from models import User, Post, db
from random import choice, randint as rand

fake = Faker()


def generate_fake_data(app):
with app.app_context():
# get the count of users, if less than 10, then genereate fake users
user_count = User.query.count()
if user_count < 10:
for i in range(10 - user_count):
user = User(
email=fake.email(),
name=fake.name(),
age=rand(18, 45),
active=choice([True, False]),
) # type: ignore
db.session.add(user)
db.session.commit()

# get list of user ids
user_ids = [user.id for user in User.query.all()]
# get the count of posts, if less than 30, then generate fake posts
post_count = Post.query.count()
if post_count < 30:
for i in range(30 - post_count):
post = Post(
author_id=choice(user_ids),
title=fake.sentence(),
body=fake.text(max_nb_chars=500)
) # type: ignore
db.session.add(post)
db.session.commit()

44 changes: 44 additions & 0 deletions examples/multiple-bootswatches/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from sqlalchemy import Column, Integer, String, ForeignKey, Text, DateTime, Boolean, func
from sqlalchemy.orm import relationship
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

db = SQLAlchemy()


class User(db.Model):
id = Column(Integer, primary_key=True)
email = Column(String(120), unique=True)
name = Column(String(64), nullable=False)
age = Column(Integer, nullable=False)
active = Column(Boolean, default=False)

created_at = Column(DateTime, default=func.now())

posts = relationship('Post', back_populates='author')

def __repr__(self):
return f'<User {self.id}>'



class Post(db.Model):
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('user.id'))
title = Column(String(64), nullable=False)
body = Column(Text)

created_at = Column(DateTime, default=func.now())

author = relationship('User', back_populates='posts')

def __repr__(self):
return f'<Post {self.id}>'



def db_init(app : Flask):
with app.app_context():
db.init_app(app)
db.create_all()

5 changes: 5 additions & 0 deletions flask_admin/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,7 @@ def __init__(self, app=None, name=None,
static_url_path=None,
base_template=None,
template_mode=None,
bootswatch_theme=None,
category_icon_classes=None):
"""
Constructor.
Expand Down Expand Up @@ -495,6 +496,9 @@ def __init__(self, app=None, name=None,
:param template_mode:
Base template path. Defaults to `bootstrap2`. If you want to use
Bootstrap 3 or 4 integration, change it to `bootstrap3` or `bootstrap4`.
:param bootswatch_theme:
Bootswatch theme to use. Defaults to `cerulean`. If you want to use
different theme, change it to the corresponding Bootswatch theme name.
:param category_icon_classes:
A dict of category names as keys and html classes as values to be added to menu category icons.
Example: {'Favorites': 'glyphicon glyphicon-star'}
Expand All @@ -519,6 +523,7 @@ def __init__(self, app=None, name=None,
self.subdomain = subdomain
self.base_template = base_template or 'admin/base.html'
self.template_mode = template_mode or 'bootstrap2'
self.bootswatch_theme = bootswatch_theme or 'cerulean'
self.category_icon_classes = category_icon_classes or dict()

# Add index view
Expand Down
2 changes: 1 addition & 1 deletion flask_admin/templates/bootstrap2/admin/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<meta name="author" content="">
{% endblock %}
{% block head_css %}
<link href="{{ admin_static.url(filename='bootstrap/bootstrap2/swatch/{swatch}/bootstrap.min.css'.format(swatch=config.get('FLASK_ADMIN_SWATCH', 'default')), v='2.3.2') }}" rel="stylesheet">
<link href="{{ admin_static.url(filename='bootstrap/bootstrap2/swatch/{swatch}/bootstrap.min.css'.format(swatch=admin_view.admin.bootswatch_theme), v='2.3.2') }}" rel="stylesheet">
<link href="{{ admin_static.url(filename='bootstrap/bootstrap2/css/bootstrap-responsive.css', v='2.3.2') }}" rel="stylesheet">
<link href="{{ admin_static.url(filename='admin/css/bootstrap2/admin.css', v='1.1.1') }}" rel="stylesheet">
{% if admin_view.extra_css %}
Expand Down
4 changes: 2 additions & 2 deletions flask_admin/templates/bootstrap3/admin/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
<meta name="author" content="">
{% endblock %}
{% block head_css %}
<link href="{{ admin_static.url(filename='bootstrap/bootstrap3/swatch/{swatch}/bootstrap.min.css'.format(swatch=config.get('FLASK_ADMIN_SWATCH', 'default')), v='3.3.5') }}" rel="stylesheet">
{%if config.get('FLASK_ADMIN_SWATCH', 'default') == 'default' %}
<link href="{{ admin_static.url(filename='bootstrap/bootstrap3/swatch/{swatch}/bootstrap.min.css'.format(swatch=admin_view.admin.bootswatch_theme), v='3.3.5') }}" rel="stylesheet">
{%if admin_view.admin.bootswatch_theme == 'default' %}
<link href="{{ admin_static.url(filename='bootstrap/bootstrap3/css/bootstrap-theme.min.css', v='3.3.5') }}" rel="stylesheet">
{%endif%}
<link href="{{ admin_static.url(filename='admin/css/bootstrap3/admin.css', v='1.1.1') }}" rel="stylesheet">
Expand Down
4 changes: 2 additions & 2 deletions flask_admin/templates/bootstrap4/admin/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
<meta name="author" content="">
{% endblock %}
{% block head_css %}
<link href="{{ admin_static.url(filename='bootstrap/bootstrap4/swatch/{swatch}/bootstrap.min.css'.format(swatch=config.get('FLASK_ADMIN_SWATCH', 'default')), v='4.2.1') }}"
<link href="{{ admin_static.url(filename='bootstrap/bootstrap4/swatch/{swatch}/bootstrap.min.css'.format(swatch=admin_view.admin.bootswatch_theme), v='4.2.1') }}"
rel="stylesheet">
{% if config.get('FLASK_ADMIN_SWATCH', 'default') == 'default' %}
{% if admin_view.admin.bootswatch_theme == 'default' %}
<link href="{{ admin_static.url(filename='bootstrap/bootstrap4/css/bootstrap.min.css', v='4.2.1') }}" rel="stylesheet">
{% endif %}
<link href="{{ admin_static.url(filename='admin/css/bootstrap4/admin.css', v='1.1.1') }}" rel="stylesheet">
Expand Down
Loading