Getting CKEditor to work with Flask Admin

后端 未结 2 449
北恋
北恋 2021-01-16 02:14

I\'m trying to make turn the Flask Admin text box into a CKEdit box, as described here. However, when I run it and go to the existing admin fields it doesn\'t show any chang

相关标签:
2条回答
  • 2021-01-16 02:18

    You can use Flask-CKEditor. It provide a CKEditorField that is exactly what you need. We need to install it first:

    $ pip install flask-ckeditor
    

    Then in your code:

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_admin import Admin
    from flask_admin.contrib.sqla import ModelView
    from flask_ckeditor import CKEditor, CKEditorField  # Step 1
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'dev'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
    
    db = SQLAlchemy(app)
    ckeditor = CKEditor(app)  # Step 2
    
    class Post(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(120))
        text = db.Column(db.Text)
    
    
    # Step 3
    class PostAdmin(ModelView):
        form_overrides = dict(text=CKEditorField)
        create_template = 'edit.html'
        edit_template = 'edit.html'
    
    admin = Admin(app, name='Flask-CKEditor demo')
    admin.add_view(PostAdmin(Post, db.session))
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    In your template (templates/edit.html):

    <!-- Step 4 -->
    {% extends 'admin/model/edit.html' %}
    
    {% block tail %}
        {{ super() }}
        {{ ckeditor.load() }}
        {# 
        If you have set the configuration variables more than CKEDITOR_SERVE_LOCAL and CKEDITOR_PKG_TYPE, 
        or you need to config the CKEditor textarea, use the line below to register the configuration.
        The name value should be the name of the CKEditor form field.
        #}
        {{ ckeditor.config(name='text') }}
    {% endblock %}
    

    Get this demo application on GitHub.

    0 讨论(0)
  • 2021-01-16 02:26

    Here is a simple working example using in-memory SQLite. There are only two files, the flask application and the edit Jinja2 html template.

    Library versions used are Flask 0.10.1, Flask-SQLAlchemy 2.1 and Flask-Admin 1.4.

    The flask application flask-ckeditor.py in the root folder:

    from flask import Flask
    from flask.ext.admin import Admin
    from flask.ext.admin.contrib.sqla import ModelView
    from flask.ext.admin.menu import MenuLink
    from flask.ext.sqlalchemy import SQLAlchemy
    from wtforms.widgets import TextArea, TextInput
    from wtforms.fields import TextAreaField
    
    app = Flask(__name__)
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
    app.config['SQLALCHEMY_ECHO'] = True
    app.config['DEBUG'] = True
    app.config['SECRET_KEY'] = 'super-secret'
    
    db = SQLAlchemy(app)
    
    
    class Test(db.Model):
        __tablename__ = 'tests'
        id = db.Column(db.Integer, primary_key=True)
        text = db.Column(db.UnicodeText)
    
    
    class CKEditorWidget(TextArea):
        def __call__(self, field, **kwargs):
            if kwargs.get('class'):
                kwargs['class'] += " ckeditor"
            else:
                kwargs.setdefault('class', 'ckeditor')
            return super(CKEditorWidget, self).__call__(field, **kwargs)
    
    
    class CKEditorField(TextAreaField):
        widget = CKEditorWidget()
    
    
    class TestAdminView(ModelView):
        form_overrides = dict(text=CKEditorField)
        can_view_details = True
        create_template = 'edit.html'
        edit_template = 'edit.html'
    
    
    @app.route('/')
    def index():
        return '<a href="/admin/">Click me to get to Admin!</a>'
    
    # Create admin
    admin = Admin(app, name='Admin')
    admin.add_view(TestAdminView(model=Test, session=db.session, category='Tables', name='Test'))
    admin.add_link(MenuLink(name='Public Website', category='', url='/'))
    
    
    def build_db():
    
        tests = [
            {
                'text': "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut</p>"
            },
            {
                'text': "<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque<p>"
            },
            {
                'text': "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium</p>"
            }
        ]
    
        db.drop_all()
        db.create_all()
    
        for test in tests:
            test_db = Test(**test)
            db.session.add(test_db)
        db.session.commit()
    
    
    @app.before_first_request
    def create_user():
        build_db()
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    The Jinja2 html template file templates/edit.html:

    {% extends 'admin/model/edit.html' %}
    
    {% block tail %}
        {{ super() }}
        <script src="http://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.0.1/ckeditor.js"></script>
    {% endblock %}
    
    0 讨论(0)
提交回复
热议问题