Welcome to Django CodeMirror’s documentation!¶
This is a Django application to embed CodeMirror.
It works exclusively from configuration sets to manage CodeMirror options and assets. A dedicated field, widget and some template tags are available to make CodeMirror instances using these configurations on any element.
Since configurations are aware of every assets to load this enable you to
use CodeMirror without a Javascript module loader (like Browserify
or
RequireJS
).
Links¶
- Read the documentation on Read the docs;
- Download its PyPi package;
- Clone it on its Github repository;
Dependancies¶
- Django >= 1.10;
- Optionally django-assets;
User’s Guide¶
Install¶
pip install djangocodemirror
In your settings file add djangocodemirror to your installed apps:
INSTALLED_APPS = ( ... 'djangocodemirror', ... )
Import default settings:
from djangocodemirror.settings import *
Optionally install django-assets to use asset bundles;
Finally you may want to change available CodeMirror configurations from settings.CODEMIRROR_SETTINGS
:
- If you need to add your own new configuration see CodeMirror configurations;
- If you just need to add/change some parameters from configurations see Configuration helper.
Examples¶
This will assume you have followed Install document.
For a HTML element¶
For this example we will attach a CodeMirror instance with restructuredtext
mode directly to a HTML element through its HTML identifier (id
).
Create a
editor.html
file:{% load djangocodemirror_tags %} <form> <textarea id="code" name="code">Lorem ipsum dolor sit amet.</textarea> </form> {% codemirror_instance 'restructuredtext' 'code_codemirror' 'code' %}
Register your view in
urls.py
file:from django.conf.urls import include, url from django.views.generic.base import TemplateView urlpatterns = [ url(r'^editor/$', TemplateView.as_view( template_name="editor.html" ), name='editor'), ]
For a form field¶
For this example we will attach a CodeMirror instance with
restructuredtext
to a form field.
Create a
forms.py
file:from django import forms from djangocodemirror.fields import CodeMirrorField class SampleForm(forms.Form): foo = CodeMirrorField(label="Foo", required=True, config_name="restructuredtext")
Create a
view.py
file:from django.views.generic.edit import FormView from django.core.urlresolvers import reverse from .forms import SampleForm class BasicSampleFormView(FormView): template_name = 'form.html' form_class = SampleForm def get_success_url(self): return reverse('codemirror-form')
Create a
form.html
file:{% load djangocodemirror_tags %} <form action="." method="post">{% csrf_token %} {{ form.as_p }} <input type="submit"> </form> {% codemirror_field_css_assets form.foo %} {% codemirror_field_js_assets form.foo %} <script> var foo_codemirror = CodeMirror.fromTextArea( document.getElementById("id_foo"), {{ form.foo|codemirror_parameters }} ); </script>
Register your view in
urls.py
file:from django.conf.urls import include, url from views import BasicSampleFormView urlpatterns = [ url(r'^form/$', BasicSampleFormView.as_view( template_name="form.html" ), name='codemirror-form'), ]
Default app settings¶
Note
Every file paths (as in settings.CODEMIRROR_BASE_JS
,
settings.CODEMIRROR_BASE_CSS
, settings.CODEMIRROR_THEMES
,
settings.CODEMIRROR_MODES
, etc..) must be relative to the static
directory.
CODEMIRROR_FIELD_INIT_JS¶
Template string for HTML Code to instanciate CodeMirror for a field.
Default value:
<script>var {varname} = CodeMirror.fromTextArea(document.getElementById("{inputid}"),{settings});</script>
Contains two template variables:
varname
: A Javascript variable name which will be set with the CodeMirror instance;inputid
: HTML element id;settings
: JSON string for CodeMirror parameters.
CODEMIRROR_SETTINGS¶
Available CodeMirror configurations.
Included configurations implement a little subset of available
CodeMirror modes plus a empty
configuration.
Default available configurations are:
css
;django
;empty
;html
;javascript
;python
;restructuredtext
;scss
;
These modes are built from CodeMirror mode demonstrations to reproduce the same behaviors.
See CodeMirror configurations to create new configurations.
CODEMIRROR_BASE_JS¶
List of CodeMirror Javascript base files that will be loaded before every other CodeMirror Javascript components.
Default value:
["CodeMirror/lib/codemirror.js"]
CODEMIRROR_BASE_CSS¶
List of CodeMirror CSS base files that will be loaded before themes.
Default value:
["CodeMirror/lib/codemirror.css"]
CODEMIRROR_THEMES¶
Available CodeMirror CSS Theme files.
Default value contains only the Ambiance theme (a dark one), so you may add yourself all your needed themes.
Default value:
{
"ambiance": "CodeMirror/theme/ambiance.css",
}
CODEMIRROR_MODES¶
Available CodeMirror Javascript mode files.
Default shipped modes are built from default configurations requirements.
CODEMIRROR_JS_ASSET_TAG¶
HTML element to load a Javascript asset. Used by template tags and widget to build assets HTML loaders.
Default value:
u'<script type="text/javascript" src="{url}"></script>'
CODEMIRROR_CSS_ASSET_TAG¶
HTML element to load a CSS asset. Used by template tags and widget to build assets HTML loaders.
Default value:
u'<link rel="stylesheet" href="{url}">'
CODEMIRROR_BUNDLE_CSS_NAME¶
Template string for Javascript bundle names where {settings_name}
will
be filled with the configuration name.
Default value:
"dcm-{settings_name}_css"
CODEMIRROR_BUNDLE_JS_NAME¶
Template string for CSS bundle names where {settings_name}
will be
filled with the configuration name.
Default value:
"dcm-{settings_name}_js"
CODEMIRROR_BUNDLE_CSS_OPTIONS¶
Option arguments used to build CSS bundles with django-assets
.
Every CSS bundles will share the same arguments (excepted for the output
one).
Default value:
{
'filters':'yui_css',
'output':'css/dcm-{settings_name}.min.css',
}
CODEMIRROR_BUNDLE_JS_OPTIONS¶
Option arguments used to build Javascript bundles with django-assets
.
Every Javascript bundles will share the same arguments (excepted for the
output
one).
Default value:
{
'filters':'yui_js',
'output':'js/dcm-{settings_name}.min.js',
}
CodeMirror configurations¶
A CodeMirror configuration is a set of parameters for a CodeMirror instance. Some of them are internal ones reserved to the manifest to control some behaviors.
Every parameter in a configuration will be given to CodeMirror instance excepted some internal ones:
- themes
- List of theme names (from
settings.CODEMIRROR_THEMES
) to load. - extra_css
- List of paths for extra CSS files to append after themes.
- addons
- List of addons paths (relative to static directory) to load before modes.
- modes
- List of mode names (from
settings.CODEMIRROR_MODES
) to load. CodeMirror will assume to use the last loaded mode if you don’t explicitely enable one usingmode
parameter. - css_bundle_name
- Bundle name for this configuration CSS assets, it will be used from django-assets bundles. Automatically filled from configuration name if not defined.
- js_bundle_name
- Bundle name for this configuration Javascript assets, it will be used from django-assets bundles. Automatically filled from configuration name if not defined.
For available configuration parameters, see the CodeMirror documentation.
Create a new configuration¶
At the end of your settings (or just after default settings are loaded) you could add:
CODEMIRROR_MODES.update({
'css': {
'modes': ['css'],
'matchBrackets': True,
'extraKeys': {"Ctrl-Space": "autocomplete"},
'addons': [
"CodeMirror/addon/edit/matchbrackets.js",
"CodeMirror/addon/hint/show-hint.js",
"CodeMirror/addon/hint/css-hint.js",
],
'extra_css': [
"CodeMirror/addon/hint/show-hint.css",
],
},
})
This configuration is allready part of the default settings, copied here just for sample.
- This reproduces CodeMirror demo for
css
mode; - You can see
matchBrackets
andextraKeys
that are CodeMirror parameters, the other ones are internal parameters to define every required assets. modes
define modes to load, here justcss
;addons
define useful CodeMirror addons to load. Addons may be required from some modes, some other ones are just for optional features;extra_css
define some additional CSS stylesheets to load that are not themes. Here it’s theshow-hint
addon CSS;
See djangocodemirror.settings
file for more examples of configurations in
CODEMIRROR_SETTINGS
.
If you plan to create a new configuration to use a mode that is not yet implemented from default configurations, you should be aware how CodeMirror and its modes work.
Configuration helper¶
Usually you will want to just use included configurations from default settings and just add some parameters on them.
codemirror_settings_update
function will help you to easily apply these
parameters on many configuration in a single act.
Obviously, this is something to use from your settings.
Examples
Sample usage to apply some parameters only every configuration from default settings:
from djangocodemirror.settings import *
from djangocodemirror.helper import codemirror_settings_update
CODEMIRROR_SETTINGS = codemirror_settings_update(CODEMIRROR_SETTINGS, {
'lineNumber': False,
'indent': 4
})
Sample usage to apply some parameters only on configuration python
and
keeping only two configurations from default settings:
from djangocodemirror.settings import *
from djangocodemirror.helper import codemirror_settings_update
CODEMIRROR_SETTINGS = codemirror_settings_update(CODEMIRROR_SETTINGS, {
'lineNumber': False,
'indent': 4
}, on=['python'], names=['css', 'python'])
Note
This helper is not able to delete parameters.
-
djangocodemirror.helper.
codemirror_settings_update
(configs, parameters, on=None, names=None)[source]¶ Return a new dictionnary of configs updated with given parameters.
You may use
on
andnames
arguments to select config or filter out some configs from returned dict.Parameters: - configs (dict) – Dictionnary of configurations to update.
- parameters (dict) – Dictionnary of parameters to apply on selected configurations.
Keyword Arguments: - on (list) – List of configuration names to select for update. If empty, all given configurations will be updated.
- names (list) – List of configuration names to keep. If not empty, only those configurations will be in returned dict. Else every configs from original dict will be present.
Returns: Dict of configurations with updated parameters.
Return type: dict
Template tags¶
codemirror_field_js_assets¶
Tag to render CodeMirror Javascript assets needed for all given fields.
Example
{% load djangocodemirror_tags %}
{% codemirror_field_js_assets form.myfield1 form.myfield2 %}
codemirror_field_css_assets¶
Tag to render CodeMirror CSS assets needed for all given fields.
Example
{% load djangocodemirror_tags %}
{% codemirror_field_css_assets form.myfield1 form.myfield2 %}
codemirror_field_js_bundle¶
Filter to get CodeMirror Javascript bundle name needed for a single field.
Example
{% load djangocodemirror_tags %}
{{ form.myfield|codemirror_field_js_bundle }}
param field: | A form field that contains a widget
|
---|---|
type field: | django.forms.fields.Field |
raises: |
|
returns: | Bundle name to load with webassets. |
rtype: | string |
codemirror_field_css_bundle¶
Filter to get CodeMirror CSS bundle name needed for a single field.
Example
{% load djangocodemirror_tags %}
{{ form.myfield|codemirror_field_css_bundle }}
param field: | A form field. |
---|---|
type field: | djangocodemirror.fields.CodeMirrorField |
raises: |
|
returns: | Bundle name to load with webassets. |
rtype: | string |
codemirror_parameters¶
Filter to include CodeMirror parameters as a JSON string for a single field.
This must be called only on an allready rendered field, meaning you must not use this filter on a field before a form. Else, the field widget won’t be correctly initialized.
Example
{% load djangocodemirror_tags %}
{{ form.myfield|codemirror_parameters }}
param field: | A form field. |
---|---|
type field: | djangocodemirror.fields.CodeMirrorField |
returns: | JSON object for parameters, marked safe for Django templates. |
rtype: | string |
codemirror_instance¶
Return HTML to init a CodeMirror instance for an element.
This will output the whole HTML needed to initialize a CodeMirror instance
with needed assets loading. Assets can be omitted with the assets
option.
Example
{% load djangocodemirror_tags %}
{% codemirror_instance 'a-config-name' 'foo_codemirror' 'foo' %}
param config_name: | |
---|---|
A registred config name. | |
type config_name: | |
string | |
param varname: | A Javascript variable name. |
type varname: | string |
param element_id: | |
An HTML element identifier (without
leading # ) to attach to a CodeMirror instance. |
|
type element_id: | |
string | |
keyword assets: | Adds needed assets before the HTML if True , else
only CodeMirror instance will be outputed. Default value is
True . |
kwtype assets: | Bool |
returns: | HTML. |
rtype: | string |
Form field widget¶
-
class
djangocodemirror.widgets.
CodeMirrorAdminWidget
(*args, **kwargs)[source]¶ Bases:
djangocodemirror.widgets.CodeMirrorWidget
CodeMirror widget suited for usage in models admins.
Act like CodeMirrorWidget but allways embed Codemirror Javascript config.
-
class
djangocodemirror.widgets.
CodeMirrorWidget
(*args, **kwargs)[source]¶ Bases:
django.forms.widgets.Textarea
Widget to add a CodeMirror or DjangoCodeMirror instance on a textarea Take the same arguments than
forms.Textarea
and accepts one suplementary optionnal arguments :Parameters: - config_name (string) – A Codemirror config name available in
settings.CODEMIRROR_SETTINGS
. Default isempty
. - embed_config (bool) – If
True
will add Codemirror Javascript config just below the input. Default isFalse
.
-
config_name
¶ For given config name.
Type: string
-
template_name
¶ Template path for widget rendering.
Type: string
-
codemirror_config
()[source]¶ Shortcut to get Codemirror parameters.
Returns: CodeMirror parameters. Return type: dict
-
codemirror_script
(inputid)[source]¶ Build CodeMirror HTML script tag which contains CodeMirror init.
Parameters: inputid (string) – Input id. Returns: HTML for field CodeMirror instance. Return type: string
-
get_codemirror_field_js
()[source]¶ Return CodeMirror HTML template from
CodeMirrorWidget.codemirror_field_js
.Returns: HTML template string. Return type: string
-
init_manifest
(name)[source]¶ Initialize a manifest instance
Parameters: name (string) – Config name to register. Returns: A manifest instance where config (from config_name
attribute) is registred.Return type: CodeMirrorManifest
-
media
¶ Adds necessary files (Js/CSS) to the widget’s medias.
Returns: Media object with all assets from registered config. Return type: django.forms.Media
- config_name (string) – A Codemirror config name available in
Developer’s Guide¶
CodeMirror manifest¶
From its registred Codemirror configurations, a manifest instance is able to:
- Return needed js files, either for all registred configs or a single one;
- Return needed css files, either for all registred configs or a single one;
- Return Codemirror configuration parameters as a dict for a registred config.
A Codemirror config is selected from its name in
settings.CODEMIRROR_SETTINGS
.
-
class
djangocodemirror.manifest.
CodeMirrorManifest
[source]¶ CodeMirror configurations manifest.
A configuration contains every parameters and assets to use with a CodeMirror instance.
-
registry
¶ Configuration registry.
Type: dict
-
default_internal_config
¶ Default internal parameters.
Type: dict
-
_internal_only
¶ Names of internal parameters only that will be exluded from CodeMirror parameters.
Type: list
-
css
(name=None)[source]¶ Returns all needed CSS filepaths for given config name (if given) or every registred config instead (if no name is given).
Keyword Arguments: name (string) – Specific config name to use instead of all. Returns: List of CSS file paths. Return type: list
-
css_bundle_names
(name=None)[source]¶ Returns all needed CSS Bundle names for given config name (if given) or every registred config instead (if no name is given).
Keyword Arguments: name (string) – Specific config name to use instead of all. Returns: List of webasset bundle names. Return type: list
-
get_codemirror_parameters
(name)[source]¶ Return CodeMirror parameters for given configuration name.
This is a reduced configuration from internal parameters.
Parameters: name (string) – Config name from available ones in settings.CODEMIRROR_SETTINGS
.Returns: Parameters. Return type: dict
-
get_config
(name)[source]¶ Return a registred configuration for given config name.
Parameters: name (string) – A registred config name.
Raises: NotRegisteredError
– If given config name does not exist inregistry.
Returns: Configuration.
Return type: dict
-
get_configs
(name=None)[source]¶ Returns registred configurations.
- If
name
argument is not given, default behavior is to return every config from all registred config; - If
name
argument is given, just return its config and nothing else;
Keyword Arguments: name (string) – Specific configuration name to return.
Raises: NotRegisteredError
– If given config name does not exist inregistry.
Returns: Configurations.
Return type: dict
- If
-
js
(name=None)[source]¶ Returns all needed Javascript filepaths for given config name (if given) or every registred config instead (if no name is given).
Keyword Arguments: name (string) – Specific config name to use instead of all. Returns: List of Javascript file paths. Return type: list
-
js_bundle_names
(name=None)[source]¶ Returns all needed Javascript Bundle names for given config name (if given) or every registred config instead (if no name is given).
Keyword Arguments: name (string) – Specific config name to use instead of all. Returns: List of webasset bundle names. Return type: list
-
register
(name)[source]¶ Register configuration for an editor instance.
Parameters: name (string) – Config name from available ones in settings.CODEMIRROR_SETTINGS
.Raises: UnknowConfigError
– If given config name does not exist insettings.CODEMIRROR_SETTINGS
.Returns: Registred config dict. Return type: dict
-
register_many
(*args)[source]¶ Register many configuration names.
Parameters: *args – Config names as strings. Returns: List of registered configs. Return type: list
-
django-assets bundles¶
If django-assets is installed, module djangocodemirror.assets
will be
automatically loaded to enable asset bundles for available configurations
settings.CODEMIRROR_SETTINGS
.
Also a variable djangocodemirror.assets.DJANGO_ASSETS_INSTALLED
will be set
to True
if django-assets is installed, else False
.
Be aware that every configurations will be bundled, you may disable configurations you don’t use to avoid too much time on bundle compress.
Configuration bundle name¶
Default behavior is to automatically fill bundle names using configuration
name within a template string (either settings.CODEMIRROR_BUNDLE_CSS_NAME
or settings.CODEMIRROR_BUNDLE_JS_NAME
).
Optionnally you can define a custom name for each of bundle kind (css or js).
If you want to disable bundles for a configuration simply set bundle names
to None
in parameters:
{ ... 'mode': 'foo', 'css_bundle_name': None, 'js_bundle_name': None, ... }
Asset tag renderer¶
Bases:
djangocodemirror.manifest.CodeMirrorManifest
A manifest extend to render Codemirror assets tags HTML.
Render HTML for a CodeMirror instance.
Since a CodeMirror instance have to be attached to a HTML element, this method requires a HTML element identifier with or without the
#
prefix, it depends from template insettings.CODEMIRROR_FIELD_INIT_JS
(default one require to not prefix with#
).Parameters: - config_name (string) – A registred config name.
- varname (string) – A Javascript variable name.
- element_id (string) – An HTML element identifier (without
leading
#
) to attach to a CodeMirror instance.
Returns: HTML to instanciate CodeMirror for a field input.
Return type: string
Render HTML tags for Javascript assets.
Returns: HTML for CSS assets from every registered config. Return type: string
Render HTML tags for Javascript assets.
Returns: HTML for Javascript assets from every registered config. Return type: string
Register config name from field widgets
Parameters: *args – Fields that contains widget djangocodemirror.widget.CodeMirrorWidget
.Returns: List of registered config names from fields. Return type: list
Render HTML tag for a given path.
Parameters: - path (string) – Relative path from static directory.
- tag_template (string) – Template string for HTML tag.
Returns: HTML tag with url from given path.
Return type: string
Given a Field or BoundField, return widget instance.
Todo
Raise an exception if given field object does not have a widget.
Parameters: field (Field or BoundField) – A field instance. Returns: Retrieved widget from given field. Return type: django.forms.widgets.Widget
Development¶
Development requirement¶
djangocodemirror is developed with:
- Test Development Driven (TDD) using Pytest;
- Respecting flake and pip8 rules using Flake8;
- Sphinx for documentation with enabled Napoleon extension (using only the Google style);
- tox to test again different Python and Django versions;
Every requirement is available in file dev_requirements.txt
(except for tox).
Install for development¶
First ensure you have Python3.5, pip and virtualenv installed, then in your console terminal type this:
mkdir djangocodemirror-dev
cd djangocodemirror-dev
make install
djangocodemirror will be installed in editable mode from the last commit on master branch.
You will need an additional Python2.7 to be able to launch tests with every tox environments.
Unittests¶
Unittests are made to works on Pytest, a shortcut in Makefile is available to start them on your current development install:
make tests
Tox¶
To ease development again multiple Python and Django versions, a tox configuration has been added. You are strongly encouraged to use it to test your pull requests.
Before using it you will need to install tox, it is recommended to install it at your system level so dependancy is not in tests requirements file:
sudo pip install tox
Then go in the djangocodemirror module directory, where live the setup.py
and tox.ini
files and execute tox:
tox
Documentation¶
You should see about sphinx-autobuild for a watcher which automatically rebuild HTML documentation when you change sources.
When installed you can use following command from docs/
directory:
make livehtml
Changelog¶
Version 2.1.0 - 2019/05/05¶
Enforce varname
formatting for CODEMIRROR_FIELD_INIT_JS
setting so it
should always be a valid Javascript variable name.
Concretely varname
is slugified and dashes are replaced by underscores so
a given varname like foo codemérror-0
is turned to foo_codemerror_0
.
This should be a safe change and resolve issues with usages inside a formset. Thanks to @abumalick for report.
Also added support with Django 2.2 and removed notices about major changes from 2.0.0 version.
Version 2.0.0 - 2018/09/28¶
Add support for Django 1.11, 2.0, 2.1 and CodeMirror 5.40.2
- Rewrite package to use
setup.cfg
; - Add support for Django 1.11, Django 2.0 and Django 2.1, close #22;
- Drop support for Django 1.8 and 1.9;
- Django 1.11 support is the last one for Python2;
- Change old demo project to more cleaner sandbox;
- Change widget to use new Django widget API;
- Upgraded included copy of CodeMirror to 5.40.2;
Version 1.1.0 - 2017/05/18¶
- Added support from Django 1.9 to 1.10, close #18;
- Added support for Python 3.5, close #19;
- Dropped support for Django 1.6 and 1.7;
Version 1.0.5 - 2016/10/16¶
- Added helper to change parameters on many configs, close #14;
Version 1.0.4 - 2016/10/11¶
- Better explicit name for internal exceptions, close #16;
Version 1.0.3 - 2016/10/10¶
- Validated support for Django 1.8 from tox tests;
- Allow to disable asset bundle on a configuration using None value on bundle names, close #15;
Version 1.0.2 - 2016/10/09¶
- A dummy bump because previous version lacked of bumping to 1.0.1;
Version 1.0.1 - 2016/10/09¶
- Fixed some minor packages flaws (MANIFEST, classifiers, etc..);
Version 1.0.0 - 2016/10/09¶
This is a major refactoring to adopt Test Driven Development, cleaner behaviors and better core API.
- Added Unittests with Py.test;
- Added documentation, close #11;
- Added tox configuration to validate support for Django 1.6 and 1.7;
- Flake8 coverage;
- Rewrited every template tags and filters;
- Better docstring for code;
- Removed all stuff about reStructuredText editor addons;
- Removed everything about the CodeMirror rst editor (may probably live again in its own app);
- Removed deprecated templates;
- Replaced old Codemirror git submodule with a static copy from
5.18.2
version, close #9; - Dropped
mode
as an internal parameter since CodeMirror can use it in many different ways (as a string for a name, as a string for a mime-type, as a dict of mode options);
Version 0.9.8 - 2016/08/24¶
Last release for previous Django CodeMirror API with CodeMirror 3.x and reStructuredText editor addons.