Skip to content Skip to sidebar Skip to footer

Getting Ckeditor To Work With Flask Admin

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 change to the

Solution 1:

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 2classPost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120))
    text = db.Column(db.Text)


# Step 3classPostAdmin(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.

Solution 2:

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)


classTest(db.Model):
    __tablename__ = 'tests'id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.UnicodeText)


classCKEditorWidget(TextArea):
    def__call__(self, field, **kwargs):
        if kwargs.get('class'):
            kwargs['class'] += " ckeditor"else:
            kwargs.setdefault('class', 'ckeditor')
        returnsuper(CKEditorWidget, self).__call__(field, **kwargs)


classCKEditorField(TextAreaField):
    widget = CKEditorWidget()


classTestAdminView(ModelView):
    form_overrides = dict(text=CKEditorField)
    can_view_details = True
    create_template = 'edit.html'
    edit_template = 'edit.html'@app.route('/')defindex():
    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='/'))


defbuild_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_requestdefcreate_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 %}

Post a Comment for "Getting Ckeditor To Work With Flask Admin"