pallets-eco / flask-admin

Simple and extensible administrative interface framework for Flask
https://flask-admin.readthedocs.io
BSD 3-Clause "New" or "Revised" License
5.75k stars 1.57k forks source link

Use base template for views OUTSIDE of BaseView? #1488

Open ghost opened 7 years ago

ghost commented 7 years ago

I am currently using Flask-admin for about 85% of my application which centers around manipulating database models.

However, for the remaining 15%, I am sticking to the style recommended on the flask website.

Now for these view functions if the layout file tries to extend the Flask-admin base template via {% extends "admin/master.html" %} I am getting a UndefinedError: 'admin_base_template' is undefined error.

I understand this is caused by the fact that I am not using ModelView or BaseView.

What are my options here?

  1. Convert ALL my view functions to using BaseView from flask-admin? I don't know if I want to do that.
  2. Maintain a separate layout file just for that 15% of view functions?

There must be a better way, right?

ljluestc commented 3 months ago

from flask import Flask, render_template
from flask_admin import Admin, base
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SECRET_KEY'] = 'your_secret_key_here'

db = SQLAlchemy(app)
admin = Admin(app, name='Admin Panel', template_mode='bootstrap3')

# Define your Flask-Admin models/views
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)

admin.add_view(ModelView(User, db.session))

# Flask-Admin template context processor for non-Flask-Admin views
@app.context_processor
def admin_context_processor():
    return dict(
        admin_base_template=base.template,
        admin_view=base._get_current_admin(),
        h=admin.helpers,
        config=admin.config,
        get_url=base.get_url
    )

# Non-Flask-Admin view function
@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)