helloflask / flask-ckeditor

CKEditor integration for Flask, including image upload, code syntax highlight, and more.
https://flask-ckeditor.readthedocs.io
MIT License
197 stars 67 forks source link

Using flask-ckeditor with flask-admin inline model? #42

Open jessesheidlower opened 4 years ago

jessesheidlower commented 4 years ago

I'm trying to use CKEditor in a Flask-Admin app, but where the field I need is in an inline model. In these cases, the Admin interface can generate any number of "add" forms, which will have id values like tablename-0-fieldname, tablename-1-fieldname, etc.

If I follow the general instructions for flask-admin integration, but set up my inline models in my ModelView subclass like:

inline_models = [(Quotation, dict(form_overrides=dict(bibliography=CKEditorField)))]

and then in my template:

{{ ckeditor.load() }} {{ ckeditor.config(name='bibliography') }}

I end up with with a textarea that looks like:

<textarea class="ckeditor form-control" id="quotations-0-bibliography" name="quotations-0-bibliography"></textarea>

However, this does not cause a CKEditor instance to exist. I note that there is no <div id="cke_text"... that I see in the sample Flask-Admin app.

Is there a simple way to get this to work? Is there a not-simple way to get this to work?

greyli commented 4 years ago

Hi, thanks for reporting on this. I'm not familiar with Flask-Admin, please add an minimal, complete, and verifiable example, then I can run and test with it.

jessesheidlower commented 4 years ago

Oh, it was your comment in the Flask-Admin docs that got me here in the first place! And there are two Flask-Admin examples in the examples directory here.

In any case: I have an MCVE that is a small modification of the "flask-admin" example in this repo. This example takes the "Post" class and adds a one-to-many "Comment" to it, and then adds Comment as an inline model to the Post class. The goal is for the text field in the Comment to have a CKEditor instance.

To run this, use the "flask-admin" example, replacing app.py with the code below, and add the template below as test_create.html. When you run app.py, go to "Post" and then select "create". You will get a form with "Title", "Text", and "Comments", this last one having an "Add Comments" button. This will inject a "New Comment" form onto the page, with a "Text" field; hitting "Add Comments" will continue to inject these forms onto the page. (This is automatic--this is just how Flask-Admin's inline_models functionality works. When you save the page, all the comments are created as relations to the post.) The question is how to get this "Text" field to be a CKEditor instance.

Thank you so much for looking this over.

app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_ckeditor import CKEditor, CKEditorField
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView

app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev'

# Create in-memory database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
ckeditor = CKEditor(app)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120))
    text = db.Column(db.Text)
    comments = db.relationship('Comment', backref='post')

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)

# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Go to Admin!</a>'

# Customized Post model admin
class PostAdmin(ModelView):
    create_template = 'test_create.html'
    inline_models = [(Comment, dict(form_overrides=dict(text=CKEditorField)))]

admin = Admin(app, name='Flask-CKEditor demo')
admin.add_view(PostAdmin(Post, db.session))

def init_db():
    """
    Populate a small db with some example entries.
    """
    db.drop_all()
    db.create_all()

    # Create sample Post
    title = "de Finibus Bonorum et Malorum - Part I"
    text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \
                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \
                exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure \
                dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt \
                mollit anim id est laborum."

    post = Post(title=title, text=text)
    db.session.add(post)
    db.session.commit()

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

new test_create.html template:

{% extends 'admin/model/create.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, it defaults to "text" in Flask-Admin.
    #}
    {{ ckeditor.config(name='comment') }}
{% endblock %}
greyli commented 4 years ago

Since the textarea is dynamically created when using inline model, I can't find a proper way to make it work with this extension. Please report this issue to Flask-Admin, maybe they can add a hook to support this feature.