Skip to content

Instantly share code, notes, and snippets.

@dengshuan
Forked from mrjoes/ckedit.py
Last active January 29, 2020 20:31
Show Gist options
  • Save dengshuan/124b5c61f33bd33a26f3 to your computer and use it in GitHub Desktop.
Save dengshuan/124b5c61f33bd33a26f3 to your computer and use it in GitHub Desktop.
Apply ckeditor(WYSIWYG rich text editor) to flask-admin textarea
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext import admin
from wtforms import TextAreaField
from wtforms.widgets import TextArea
from flask.ext.admin.contrib.sqla import ModelView
app = Flask(__name__)
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.sqlite'
db = SQLAlchemy(app)
class CKTextAreaWidget(TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
return super(CKTextAreaWidget, self).__call__(field, **kwargs)
class CKTextAreaField(TextAreaField):
widget = CKTextAreaWidget()
class Test(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.UnicodeText)
class TestAdmin(ModelView):
form_overrides = dict(text=CKTextAreaField)
create_template = 'edit.html'
edit_template = 'edit.html'
if __name__ == '__main__':
admin = admin.Admin(app)
admin.add_view(TestAdmin(Test, db.session))
db.create_all()
app.debug = True
app.run('0.0.0.0', 8000)
{% extends 'admin/model/edit.html' %}
{% block tail %}
{{ super() }}
<script src="http://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.0.1/ckeditor.js"></script>
{% endblock %}
@dengshuan
Copy link
Author

Flask-WTF and SQLAlchemy new versions has changed their API, so I update the original gist created by mrjoes(https://gist.github.com/mrjoes/5189850).
To try this gist, download this two files, put edit.html in templates directory and run this gist by pyhton ckedit.py

@cybertoast
Copy link

In order to make this example work with the bootstrap3 template in Flask-admin, do the following:

class CKTextAreaWidget(TextArea):
    def __call__(self, field, **kwargs):
        if kwargs.get('class'):
            kwargs['class'] += " ckeditor"
        else:
            kwargs.setdefault('class', 'ckeditor')
        return super(CKTextAreaWidget, self).__call__(field, **kwargs)

And change the Admin() initialization call as follows:

admin = admin.Admin(app, template_mode='bootstrap3')

@iilxy
Copy link

iilxy commented Apr 19, 2015

Thank you both !!!

@dremendes
Copy link

Still working fine, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment