Getting CKEditor to work with Flask Admin

后端 未结 2 477
北恋
北恋 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):

    
    {% 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.

提交回复
热议问题