Beispiel #1
0
class PageForm(forms.ModelForm):
    class Meta:
        model = Page
        fields = [
            'user', 'title', 'description', 'slug', 'public', 'sample',
            'assignment', 'tags', 'htmlHead', 'htmlBody', 'css', 'javascript'
        ]

    htmlHead = forms.CharField(
        widget=CodeMirrorTextarea(mode="xml"),
        required=False,
    )
    htmlBody = forms.CharField(
        widget=CodeMirrorTextarea(mode="xml"),
        required=False,
    )
    css = forms.CharField(
        widget=CodeMirrorTextarea(mode="css"),
        required=False,
    )
    javascript = forms.CharField(
        widget=CodeMirrorTextarea(mode="javascript"),
        required=False,
    )

    tags = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                          queryset=Tag.objects.all(),
                                          required=False)
Beispiel #2
0
 class Meta:
     model = Processor
     widgets = {
         'parameters':
         CodeMirrorTextarea(
             mode='yaml',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         ),
         'requirements':
         CodeMirrorTextarea(
             mode='shell',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         ),
         'accept_code':
         CodeMirrorTextarea(
             mode='python',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         ),
         'process_code':
         CodeMirrorTextarea(
             mode='python',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         ),
     }
Beispiel #3
0
class RideAdmin(admin.ModelAdmin):
    inlines = (RiderInline,)
    ordering = ['-start_date']
    list_display = ('name', 'start_date', 'end_date', 'price', 'currency', 'rider_capacity', 'spaces_left')
    list_filter = ('start_date',)
    formfield_overrides = {
        models.TextField: {'widget': CodeMirrorTextarea(mode='markdown', config={'lineWrapping': True, 'lineNumbers': False})}
    }
    fieldsets = [
        (None, {
            'classes': ('suit-tab', 'suit-tab-details',),
            'fields': ['name', 'slug', 'start_location', 'end_location', 'start_date', 'end_date', 'rider_capacity', 'preregistration_required',
                       'price', 'full_cost', 'currency', 'chapter', 'fundraising_target', 'just_giving_event_id', 'mailchimp_group_id',]
        }),
        (None, {
            'classes': ('suit-tab', 'suit-tab-description',),
            'fields': ['strapline', 'description',]}),
        (None, {
            'classes': ('suit-tab', 'suit-tab-terms',),
            'fields': ['terms_and_conditions']}),
        (None, {
            'classes': ('suit-tab', 'suit-tab-riders',),
            'fields': []}),
    ]
    suit_form_tabs = (('details', 'Details'), ('description', 'Description'), ('terms', 'Terms & Conditions'), ('riders', 'Riders'))
Beispiel #4
0
    def __init__(self, read_only, initial_code, *args, **kwargs):
        super(PythonCodeForm, self).__init__(*args, **kwargs)

        from codemirror import CodeMirrorTextarea, CodeMirrorJavascript

        theme = "default"
        if read_only:
            theme += " relate-readonly"

        self.fields["answer"] = forms.CharField(
            required=True,
            initial=initial_code,
            help_text="Hit F9 to toggle full screen mode.",
            widget=CodeMirrorTextarea(
                mode="python",
                theme=theme,
                addon_css=(
                    "dialog/dialog",
                    "display/fullscreen",
                ),
                addon_js=(
                    "search/searchcursor",
                    "dialog/dialog",
                    "search/search",
                    "edit/matchbrackets",
                    "comment/comment",
                    "display/fullscreen",
                    "selection/active-line",
                ),
                config={
                    "fixedGutter":
                    True,
                    "indentUnit":
                    4,
                    "matchBrackets":
                    True,
                    "styleActiveLine":
                    True,
                    "readOnly":
                    read_only,
                    # "autofocus": not read_only,
                    "extraKeys":
                    CodeMirrorJavascript("""
                        {
                          "Ctrl-/": "toggleComment",
                          "Tab": function(cm)
                          {
                            var spaces = \
                                    Array(cm.getOption("indentUnit") + 1).join(" ");
                            cm.replaceSelection(spaces);
                          },
                          "F9": function(cm) {
                              cm.setOption("fullScreen",
                                !cm.getOption("fullScreen"));
                          }
                        }
                    """)
                }),
        )
Beispiel #5
0
    def set_editor_field_widget(self, field_name, mode):
        """ Create a field widget and set attributes accordingly. """

        self.fields[field_name].widget = CodeMirrorTextarea(
            mode=mode,
            addon_js=settings.CODEMIRROR_ADDONS_JS,
            addon_css=settings.CODEMIRROR_ADDONS_CSS,
            keymap=settings.CODEMIRROR_KEYMAP,
        )
Beispiel #6
0
 class Meta:
     model = ChainedItem
     fields = ('parameters', )
     widgets = {
         'parameters': CodeMirrorTextarea(
             mode='yaml',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         )
     }
Beispiel #7
0
 class Meta:
     model = BaseFeed
     fields = ('processing_parameters', )
     widgets = {
         'processing_parameters': CodeMirrorTextarea(
             mode='yaml',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         )
     }
Beispiel #8
0
 class Meta:
     model = Processor
     fields = ('requirements', )
     widgets = {
         'requirements':
         CodeMirrorTextarea(
             mode='shell',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         )
     }
Beispiel #9
0
 class Meta:
     model = Processor
     fields = ('accept_code', )
     widgets = {
         'accept_code':
         CodeMirrorTextarea(
             mode='python',
             addon_js=settings.CODEMIRROR_ADDONS_JS,
             addon_css=settings.CODEMIRROR_ADDONS_CSS,
             keymap=settings.CODEMIRROR_KEYMAP,
         ),
     }
Beispiel #10
0
class TemplateForm(forms.Form):
    def __init__(self, content, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['content'].initial = content
        self.fields['content'].label = ''

    content = forms.CharField(widget=CodeMirrorTextarea(
        mode='htmlmixed',
        theme='base16-dark',
        config={
            'fixedGutter': True,
        },
        dependencies=('xml', 'javascript', 'css'),
    ), )
Beispiel #11
0
def python_widget(readonly=False, attrs=None):  # FIXME: support folded
    config = CONFIG.copy()
    config.update({
        'readOnly': readonly,
        'styleActiveLine': not readonly,
    })
    return CodeMirrorTextarea(attrs=attrs,
                              mode={
                                  'name': 'python',
                                  'singleLineStringErrors': True
                              },
                              theme=THEME,
                              addon_js=ADDON_JS,
                              config=config)
Beispiel #12
0
def json_widget(readonly=False, attrs=None):  # FIXME: support folded
    config = CONFIG.copy()
    config.update({
        'readOnly': readonly,
        'styleActiveLine': not readonly,
    })
    return CodeMirrorTextarea(attrs=attrs,
                              mode={
                                  'name': 'javascript',
                                  'json': True
                              },
                              theme=THEME,
                              addon_js=ADDON_JS,
                              addon_css=ADDON_CSS,
                              config=config)
Beispiel #13
0
 class Meta:
     model = CategoryTemplate
     fields = '__all__'
     widgets = {
         'body':
         CodeMirrorTextarea(
             mode="django",
             dependencies=("xml", 'htmlmixed'),
             addon_js=("mode/overlay", ),
             theme="mdn-like",
             custom_css=("css/category_template_code_widget.css", ),
             config={
                 'lineNumbers': True,
                 'tabSize': 2,
                 'indentWithTabs': True
             })
     }
class CodeForm(forms.Form):
    codemirror_widget = CodeMirrorTextarea(mode="python", theme="cobalt", config={ 'fixedGutter': True })
    document = forms.CharField(widget=codemirror_widget)
Beispiel #15
0
    def get_text_widget(widget_type, read_only=False, check_only=False):
        """Returns None if no widget found."""

        if widget_type in [None, "text_input"]:
            if check_only:
                return True

            widget = forms.TextInput()
            widget.attrs["autofocus"] = None
            if read_only:
                widget.attrs["readonly"] = None
            return widget

        elif widget_type == "textarea":
            if check_only:
                return True

            widget = forms.Textarea()
            # widget.attrs["autofocus"] = None
            if read_only:
                widget.attrs["readonly"] = None
            return widget

        elif widget_type in ["editor:markdown", "editor:yaml"]:
            if check_only:
                return True

            editor_mode = widget_type[widget_type.find(":") + 1:]

            theme = "default"
            if read_only:
                theme += " relate-readonly"

            from codemirror import CodeMirrorTextarea, CodeMirrorJavascript
            return CodeMirrorTextarea(
                mode=editor_mode,
                theme=theme,
                addon_css=(
                    "dialog/dialog",
                    "display/fullscreen",
                ),
                addon_js=(
                    "search/searchcursor",
                    "dialog/dialog",
                    "search/search",
                    "edit/matchbrackets",
                    "display/fullscreen",
                    "selection/active-line",
                ),
                config={
                    "fixedGutter":
                    True,
                    # "autofocus": True,
                    "matchBrackets":
                    True,
                    "styleActiveLine":
                    True,
                    "indentUnit":
                    2,
                    "readOnly":
                    read_only,
                    "extraKeys":
                    CodeMirrorJavascript("""
                            {
                              "Tab": function(cm)
                              {
                                var spaces = \
                                    Array(cm.getOption("indentUnit") + 1).join(" ");
                                cm.replaceSelection(spaces);
                              },
                              "F9": function(cm) {
                                  cm.setOption("fullScreen",
                                    !cm.getOption("fullScreen"));
                              },
                            }
                        """)
                })

        else:
            return None
Beispiel #16
0
 def formfield(self, **kwargs):
     field = super(SQLField, self).formfield(**kwargs)
     field.widget = CodeMirrorTextarea(mode="text/x-sql", theme="mdn-like")
     return field
Beispiel #17
0
    def __init__(self, initial_text,
            editor_mode, vim_mode, help_text, *args, **kwargs):
        super(SandboxForm, self).__init__(*args, **kwargs)

        from crispy_forms.helper import FormHelper
        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"

        from codemirror import CodeMirrorTextarea, CodeMirrorJavascript

        self.fields["content"] = forms.CharField(
                required=False,
                initial=initial_text,
                widget=CodeMirrorTextarea(
                    mode=editor_mode,
                    theme="default",
                    addon_css=(
                        "dialog/dialog",
                        "display/fullscreen",
                        ),
                    addon_js=(
                        "search/searchcursor",
                        "dialog/dialog",
                        "search/search",
                        "edit/matchbrackets",
                        "display/fullscreen",
                        "selection/active-line",
                        "edit/trailingspace",
                        ),
                    config={
                        "fixedGutter": True,
                        "autofocus": True,
                        "matchBrackets": True,
                        "styleActiveLine": True,
                        "showTrailingSpace": True,
                        "indentUnit": 2,
                        "vimMode": vim_mode,
                        "extraKeys": CodeMirrorJavascript("""
                            {
                              "Tab": function(cm)
                              {
                                var spaces = \
                                    Array(cm.getOption("indentUnit") + 1).join(" ");
                                cm.replaceSelection(spaces);
                              },
                              "F9": function(cm) {
                                  cm.setOption("fullScreen",
                                    !cm.getOption("fullScreen"));
                              }
                            }
                        """)
                    }),
                help_text=mark_safe(
                    help_text + " Press Alt/Cmd+(Shift+)P to preview. "
                    "Press F9 to toggle full screen mode."))

        self.fields["vim_mode"] = forms.BooleanField(
                required=False, initial=vim_mode)

        self.helper.add_input(
                Submit(
                    "preview", "Preview",
                    accesskey="p"))
Beispiel #18
0
def get_codemirror_widget(language_mode,
                          interaction_mode,
                          config=None,
                          addon_css=(),
                          addon_js=(),
                          dependencies=(),
                          read_only=False):
    theme = "default"
    if read_only:
        theme += " relate-readonly"

    from codemirror import CodeMirrorTextarea, CodeMirrorJavascript

    from django.core.urlresolvers import reverse
    help_text = (_("Press F9 to toggle full-screen mode. ") +
                 _("Set editor mode in <a href='%s'>user profile</a>.") %
                 reverse("relate-user_profile"))

    actual_addon_css = (
        "dialog/dialog",
        "display/fullscreen",
    ) + addon_css
    actual_addon_js = (
        "search/searchcursor",
        "dialog/dialog",
        "search/search",
        "comment/comment",
        "edit/matchbrackets",
        "display/fullscreen",
        "selection/active-line",
        "edit/trailingspace",
    ) + addon_js

    if language_mode == "python":
        indent_unit = 4
    else:
        indent_unit = 2

    actual_config = {
        "fixedGutter":
        True,
        #"autofocus": True,
        "matchBrackets":
        True,
        "styleActiveLine":
        True,
        "showTrailingSpace":
        True,
        "indentUnit":
        indent_unit,
        "readOnly":
        read_only,
        "extraKeys":
        CodeMirrorJavascript("""
                {
                  "Ctrl-/": "toggleComment",
                  "Tab": function(cm)
                  {
                    var spaces = \
                        Array(cm.getOption("indentUnit") + 1).join(" ");
                    cm.replaceSelection(spaces);
                  },
                  "F9": function(cm) {
                      cm.setOption("fullScreen",
                        !cm.getOption("fullScreen"));
                  }
                }
            """)
    }

    if interaction_mode == "vim":
        actual_config["vimMode"] = True
        actual_addon_js += ('../keymap/vim', )
    elif interaction_mode == "emacs":
        actual_config["keyMap"] = "emacs"
        actual_addon_js += ('../keymap/emacs', )
    elif interaction_mode == "sublime":
        actual_config["keyMap"] = "sublime"
        actual_addon_js += ('../keymap/sublime', )
    # every other interaction mode goes to default

    if config is not None:
        actual_config.update(config)

    return CodeMirrorTextarea(mode=language_mode,
                              dependencies=dependencies,
                              theme=theme,
                              addon_css=actual_addon_css,
                              addon_js=actual_addon_js,
                              config=actual_config), help_text
Beispiel #19
0
codemirror_json_widget = CodeMirrorJSONField(mode="css",
                                             theme="elegant",
                                             config={
                                                 'fixedGutter': True,
                                                 'lineNumbers': True,
                                                 'matchBrackets': True,
                                                 'autoCloseBrackets': True,
                                                 'lineWrapping': True
                                             })

codemirror_md_widget = CodeMirrorTextarea(mode="markdown",
                                          theme="elegant",
                                          config={
                                              'fixedGutter': True,
                                              'lineNumbers': True,
                                              'matchBrackets': True,
                                              'autoCloseBrackets': True,
                                              'lineWrapping': True
                                          })


class BlogTagsListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('type of blogpost')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'type-of-blogpost'

    def lookups(self, request, model_admin):
Beispiel #20
0
def get_codemirror_widget(
        language_mode,  # type: Text
        interaction_mode,  # type: Text
        config=None,  # type: Optional[Dict]
        addon_css=(),  # type: Tuple
        addon_js=(),  # type: Tuple
        dependencies=(),  # type: Tuple
        read_only=False,  # type: bool
        ):
    # type: (...) ->  CodeMirrorTextarea
    theme = "default"
    if read_only:
        theme += " relate-readonly"

    from django.urls import reverse
    help_text = (_("Press F9 to toggle full-screen mode. ")
            + _("Set editor mode in <a href='%s'>user profile</a>.")
            % reverse("relate-user_profile"))

    actual_addon_css = (
        "dialog/dialog",
        "display/fullscreen",
        ) + addon_css
    actual_addon_js = (
        "search/searchcursor",
        "dialog/dialog",
        "search/search",
        "comment/comment",
        "edit/matchbrackets",
        "display/fullscreen",
        "selection/active-line",
        "edit/trailingspace",
        ) + addon_js

    if language_mode == "python":
        indent_unit = 4
    else:
        indent_unit = 2

    actual_config = {
            "fixedGutter": True,
            #"autofocus": True,
            "matchBrackets": True,
            "styleActiveLine": True,
            "showTrailingSpace": True,
            "indentUnit": indent_unit,
            "readOnly": read_only,
            "extraKeys": CodeMirrorJavascript("""
                {
                  "Ctrl-/": "toggleComment",
                  "Tab": function(cm)
                  {
                    // from https://github.com/codemirror/CodeMirror/issues/988

                    if (cm.doc.somethingSelected()) {
                        return CodeMirror.Pass;
                    }
                    var spacesPerTab = cm.getOption("indentUnit");
                    var spacesToInsert = (
                        spacesPerTab
                        - (cm.doc.getCursor("start").ch % spacesPerTab));
                    var spaces = Array(spacesToInsert + 1).join(" ");
                    cm.replaceSelection(spaces, "end", "+input");
                  },
                  "Shift-Tab": "indentLess",
                  "F9": function(cm) {
                      cm.setOption("fullScreen",
                        !cm.getOption("fullScreen"));
                  }
                }
            """)
            }

    if interaction_mode == "vim":
        actual_config["vimMode"] = True
        actual_addon_js += ('../keymap/vim',)
    elif interaction_mode == "emacs":
        actual_config["keyMap"] = "emacs"
        actual_addon_js += ('../keymap/emacs',)
    elif interaction_mode == "sublime":
        actual_config["keyMap"] = "sublime"
        actual_addon_js += ('../keymap/sublime',)
    # every other interaction mode goes to default

    if config is not None:
        actual_config.update(config)

    return CodeMirrorTextarea(
                    mode=language_mode,
                    dependencies=dependencies,
                    theme=theme,
                    addon_css=actual_addon_css,
                    addon_js=actual_addon_js,
                    config=actual_config), help_text
Beispiel #21
0
from codemirror import CodeMirrorTextarea
from core.models import PDF
from django import forms

codemirror_widget = CodeMirrorTextarea(mode="xml",
                                       custom_css=("codemirror/custom.css", ))


class PdfForm(forms.ModelForm):
    html = forms.CharField(widget=codemirror_widget)

    class Meta:
        model = PDF
        fields = "__all__"
Beispiel #22
0
def get_codemirror_widget():
    # type: (...) ->  CodeMirrorTextarea

    theme = "default"

    addon_css = (
        "dialog/dialog",
        "display/fullscreen",
    )
    addon_js = (
        "search/searchcursor",
        "dialog/dialog",
        "search/search",
        "comment/comment",
        "edit/matchbrackets",
        "display/fullscreen",
        "selection/active-line",
        "edit/trailingspace",
    )

    indent_unit = 2

    config = {
        "autofocus":
        True,
        "fixedGutter":
        True,
        "matchBrackets":
        True,
        "styleActiveLine":
        True,
        "showTrailingSpace":
        True,
        "indentUnit":
        indent_unit,
        "readOnly":
        False,
        "extraKeys":
        CodeMirrorJavascript("""
                {
                  "Ctrl-/": "toggleComment",
                  "Tab": function(cm)
                  {
                    // from https://github.com/codemirror/CodeMirror/issues/988

                    if (cm.doc.somethingSelected()) {
                        return CodeMirror.Pass;
                    }
                    var spacesPerTab = cm.getOption("indentUnit");
                    var spacesToInsert = (
                        spacesPerTab
                        - (cm.doc.getCursor("start").ch % spacesPerTab));
                    var spaces = Array(spacesToInsert + 1).join(" ");
                    cm.replaceSelection(spaces, "end", "+input");
                  },
                  "Shift-Tab": "indentLess",
                  "F9": function(cm) {
                      cm.setOption("fullScreen",
                        !cm.getOption("fullScreen"));
                  }
                }
            """)
    }

    return CodeMirrorTextarea(mode="stex",
                              theme=theme,
                              addon_css=addon_css,
                              addon_js=addon_js,
                              config=config)
Beispiel #23
0
from django import forms
from codemirror import CodeMirrorTextarea

widget = CodeMirrorTextarea(mode="python",
                            theme="cobalt",
                            config={
                                "fixedGutter": True,
                            })


class SampleForm(forms.Form):
    body = forms.CharField(label="Body", widget=widget)