Skip to main content
Join the official 2019 Python Developers SurveyStart the survey!

Use CodeMirror Javascript library with Flask-WTF

Project description

version license

Implementation of source code editor for Flask and Flask-WTF using CodeMirror Javascript library

Installation

$ pip install flask-codemirror

Example

A simple example of how to use this module

from flask_wtf import FlaskForm
from flask_codemirror.fields import CodeMirrorField
from wtforms.fields import SubmitField

class MyForm(FlaskForm):
    source_code = CodeMirrorField(language='python', config={'lineNumbers': 'true'})
    submit = SubmitField('Submit')

The CodeMirrorField works exactly like a TextAreaField

@app.route('/', methods = ['GET', 'POST'])
def index():
    form = MyForm()
    if form.validate_on_submit():
        text = form.source_code.data
    return render_template('index.html', form=form)

The module needs to be initialized in the usual way and can be configured using app.config keys

from flask import Flask
from flask_codemirror import CodeMirror
# mandatory
CODEMIRROR_LANGUAGES = ['python', 'html']
WTF_CSRF_ENABLED = True
SECRET_KEY = 'secret'
# optional
CODEMIRROR_THEME = '3024-day'
CODEMIRROR_ADDONS = (
        ('ADDON_DIR','ADDON_NAME'),
)
app = Flask(__name__)
app.config.from_object(__name__)
codemirror = CodeMirror(app)

The config CODEMIRROR_LANGUAGES needs to be initialized to load JavaScript. It defined all the languages you want to edit with your fields. The config CODEMIRROR_THEME is optional and is used to style your TextArea using css from CodeMirror website. The config CODEMIRROR_ADDONS is optional and can enable many cool options see Codemirror Addons for available addons.

Finally, the template needs the support Javascript code added, by calling codemirror.include_codemirror() :

<html>
  <head>
    {{ codemirror.include_codemirror() }}
  </head>
  <body>
    <form method="POST">
       {{ form.source_code }}
       <input type="submit" value="OK">
    </form>
  </body>
</html>

The Javascript classes are imported from a CDN, there are no static files that need to be served by the application.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for flask-codemirror, version 1.1
Filename, size File type Python version Upload date Hashes
Filename, size flask_codemirror-1.1-py2.py3-none-any.whl (9.0 kB) File type Wheel Python version py2.py3 Upload date Hashes View hashes
Filename, size flask-codemirror-1.1.tar.gz (22.2 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page