Esempio n. 1
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"

        mce_config = self.profile.copy()
        #mce_config.update(get_language_config(self.content_language))
        #if tinymce.settings.USE_FILEBROWSER:
            #mce_config['file_browser_callback'] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        mce_config['selector'] = '#%s' % final_attrs['id']
        
        # Fix for js functions
        #js_functions = {}
        #for k in ('paste_preprocess','paste_postprocess'):
            #if k in mce_config:
               #js_functions[k] = mce_config[k]
               #del mce_config[k]
        mce_json = json.dumps(mce_config)

        #for k in js_functions:
            #index = mce_json.rfind('}')
            #mce_json = mce_json[:index]+', '+k+':'+js_functions[k].strip()+mce_json[index:]

        if mce_config.get('inline', False):
            html = [u'<div%s>%s</div>' % (flatatt(final_attrs), escape(value))]
        else:
            html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))]
        html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json)

        return mark_safe(u'\n'.join(html))
Esempio n. 2
0
    def render(self, name, value, attrs=None):
        """
        Renders this widget into an HTML string
        
        :param name:  Name of the field
        :type name:   str
        :param value: A json string of a two-tuple list automatically passed in by django
        :type value:  str
        :param attrs: automatically passed in by django (unused in this function)
        :type attrs:  dict
        """
        if value is None or value is '':
            value = '{}'
        if type(value) == type({}):
            twotuple = value.items()
        else:
            twotuple = simplejson.loads(force_unicode(value))

        ret = []
        if value and len(value) > 0:
            for k, v in twotuple:
                ctx = {
                    'key': k,
                    'value': v,
                    'fieldname': name,
                    'key_attrs': flatatt(self.key_attrs),
                    'val_attrs': flatatt(self.val_attrs)
                }
                ret.append(
                    '<input type="text" name="json_key[%(fieldname)s]" value="%(key)s" %(key_attrs)s> <input type="text" name="json_value[%(fieldname)s]" value="%(value)s" %(val_attrs)s><br />'
                    % ctx)
        return mark_safe("".join(ret))
Esempio n. 3
0
 def render(self, name, value, attrs=None):
     """
     Renders this widget into an HTML string
     
     :param name:  Name of the field
     :type name:   str
     :param value: A json string of a two-tuple list automatically passed in by django
     :type value:  str
     :param attrs: automatically passed in by django (unused in this function)
     :type attrs:  dict
     """
     if value is None or value is '': 
         value = '{}'
     if type(value) == type({}):
         twotuple = value.items()
     else:
         twotuple = simplejson.loads(force_unicode(value))
     
     ret = []
     if value and len(value) > 0:
         for k,v in twotuple:
             ctx = {'key':k,
                    'value':v,
                    'fieldname':name,
                    'key_attrs': flatatt(self.key_attrs),
                    'val_attrs': flatatt(self.val_attrs) }
             ret.append('<input type="text" name="json_key[%(fieldname)s]" value="%(key)s" %(key_attrs)s> <input type="text" name="json_value[%(fieldname)s]" value="%(value)s" %(val_attrs)s><br />' % ctx)
     return mark_safe("".join(ret))
Esempio n. 4
0
def render_label(content, label_for=None, label_class=None, label_title=''):
    attrs = {}
    if label_for:
        attrs['for'] = label_for
    if label_class:
        attrs['class'] = label_class
    if label_title:
        attrs['title'] = label_title
    # content = ''
    if content.__class__ == unicode:
        return u'<label {0}>{1}</label>'.format(
            flatatt(attrs),
            content,
        )
    else:
        try:
            return u'<label {0}>{1}</label>'.format(
                flatatt(attrs),
                content.decode('utf-8'),
            )
        except UnicodeEncodeError:
            return u'<label {0}>{1}</label>'.format(
                flatatt(attrs),
                content.__unicode__(),
            )
    def render(self, name, value=None, attrs=None):
        value_id = 'id_%s' % name  # id_fieldname
        label_id = '%s_autocomplete' % value_id  # id_fieldname_autocomplete

        value_attrs = dict(id=value_id, name=name, value=value or '')

        # attrs is consumed by the label field (autocomplete)
        if value:
            label_value = str(self.model.objects.get(pk=value))
        else:
            label_value = ''
        label_attrs = dict(id=label_id, name='%s_autocomplete' % name, value=label_value)

        html = u'''
        <input type="hidden" %(value_attrs)s />
        <input type="text" %(label_attrs)s />

        %(select)s
        ''' % {'value_attrs': flatatt(value_attrs),
               'label_attrs': flatatt(label_attrs),
               'select': self.render_select(value_id)}

        html += u'''
        <script type="text/javascript"><!--//
            $(document).ready(function(){
                %(js)s
            });
        //--></script>
        ''' % {'js': self.render_js(label_id, value_id)}
        return html
Esempio n. 6
0
    def render(self, name, value=None, attrs=None):
        value_id = 'id_%s' % name  # id_fieldname
        label_id = '%s_autocomplete' % value_id  # id_fieldname_autocomplete

        if not value:
            value = ""

        value_attrs = dict(id=value_id, name=name, value=value)

        # attrs is consumed by the label field (autocomplete)
        label_attrs = self.build_attrs(attrs)  # must not have 'name' attribute
        if value and value != 'None':
            label_attrs['value'] = self.model.objects.get(id=value)
        else:
            label_attrs['value'] = ''
        if not 'id' in self.attrs:
            label_attrs['id'] = label_id

        html = u'''
        <input type="hidden" %(value_attrs)s />
        <input type="text" %(label_attrs)s />
        <script type="text/javascript"><!--//
          %(js)s
        //--></script>
        ''' % {
            'value_attrs': flatatt(value_attrs),
            'label_attrs': flatatt(label_attrs),
            'js': self.render_js(label_id, value_id),
        }
        return html
Esempio n. 7
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"

        mce_config = self.profile.copy()
        #mce_config.update(get_language_config(self.content_language))
        #if tinymce.settings.USE_FILEBROWSER:
            #mce_config['file_browser_callback'] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        mce_config['selector'] = '#%s' % final_attrs['id']
        
        # Fix for js functions
        #js_functions = {}
        #for k in ('paste_preprocess','paste_postprocess'):
            #if k in mce_config:
               #js_functions[k] = mce_config[k]
               #del mce_config[k]
        mce_json = json.dumps(mce_config)

        #for k in js_functions:
            #index = mce_json.rfind('}')
            #mce_json = mce_json[:index]+', '+k+':'+js_functions[k].strip()+mce_json[index:]

        if mce_config.get('inline', False):
            html = [u'<div%s>%s</div>' % (flatatt(final_attrs), escape(value))]
        else:
            html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))]
        html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json)

        return mark_safe(u'\n'.join(html))
Esempio n. 8
0
    def render(self, name, value, attrs=None):
        """Renders this widget into an html string

        args:
        name  (str)  -- name of the field
        value (str)  -- a json string of a two-tuple list automatically passed in by django
        attrs (dict) -- automatically passed in by django (unused in this function)
        """

        if value is None or value.strip() is "":
            value = "{}"
        twotuple = simplejson.loads(force_unicode(value))

        ret = ""
        if value and len(value) > 0:
            for k, v in twotuple:
                ctx = {
                    "key": k,
                    "value": v,
                    "fieldname": name,
                    "key_attrs": flatatt(self.key_attrs),
                    "val_attrs": flatatt(self.val_attrs),
                }
                ret += (
                    '<input type="text" name="json_key[%(fieldname)s]" value="%(key)s" %(key_attrs)s> <input type="text" name="json_value[%(fieldname)s]" value="%(value)s" %(val_attrs)s><br />'
                    % ctx
                )
        return mark_safe(ret)
    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = []
        final_attrs = self.build_attrs(attrs, name=name)

        # Pop id
        id = final_attrs['id']
        del final_attrs['id']

        # Insert blank value
        choices = [('','---')] + list(self.choices)

        # Build values
        items = []
        for val in value:
            opts = "\n".join([TPL_OPTION %{'value': k, 'desc': v, 'selected': val == k and 'selected="selected"' or ''} for k, v in choices])

            items.append(TPL_SELECT %{'attrs': flatatt(final_attrs), 'opts': opts})

        # Build blank value
        opts = "\n".join([TPL_OPTION %{'value': k, 'desc': v, 'selected': ''} for k, v in choices])
        items.append(TPL_SELECT %{'attrs': flatatt(final_attrs), 'opts': opts})

        script = TPL_SCRIPT %{'id': id}
        output = TPL_FULL %{'id': id, 'values': '\n'.join(items), 'script': script}

        return mark_safe(output)
    def render(self, name, value=None, attrs=None):
        value_id = 'id_%s' % name  # id_fieldname
        label_id = '%s_autocomplete' % value_id  # id_fieldname_autocomplete

        if not value:
            value = ""

        value_attrs = dict(id=value_id, name=name, value=value)

        # attrs is consumed by the label field (autocomplete)
        label_attrs = self.build_attrs(attrs)  # must not have 'name' attribute
        if value and value != 'None':
            label_attrs['value'] = self.model.objects.get(id=value)
        else:
            label_attrs['value'] = ''
        if not 'id' in self.attrs:
            label_attrs['id'] = label_id

        html = u'''
        <input type="hidden" %(value_attrs)s />
        <input type="text" %(label_attrs)s />
        <script type="text/javascript"><!--//
          %(js)s
        //--></script>
        ''' % {
            'value_attrs': flatatt(value_attrs),
            'label_attrs': flatatt(label_attrs),
            'js': self.render_js(label_id, value_id),
        }
        return html
Esempio n. 11
0
 def render(self, name, value, attrs=None):
     input_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     icon_attrs = dict([(key, conditional_escape(val))
                        for key, val in self.icon_attrs.items()])
     if not self.picker_id:
         self.picker_id = (input_attrs.get('id', '') + '_pickers').replace(
             ' ', '_')
     self.div_attrs['id'] = self.picker_id
     if not self.js_var:
         self.js_var = (input_attrs.get('id', '') + '_jsvar').replace(
             ' ', '_')
         self.js_var = self.js_var.replace('-', '_')
     div = self.div()
     div = format_html(div,
                       div_attrs=flatatt(self.div_attrs),
                       icon_attrs=flatatt(icon_attrs))
     input_ = self.input()
     input_ = format_html(input_, input_attrs=flatatt(input_attrs))
     js = self.js()
     # hopefully this is correct...
     js = js.format(var_name=self.js_var,
                    picker_id=self.picker_id,
                    input_id=input_attrs['id'],
                    options=json.dumps(self.options))
     content = div + '\n' + input_ + '\n' + js
     return mark_safe(force_text(content))
Esempio n. 12
0
 def render_pair(self, key, value, name):
     ctx = {
         'key': key,
         'value': value,
         'fieldname': name,
         'key_attrs': flatatt(self.attrs['key_attrs']),
         'val_attrs': flatatt(self.attrs['val_attrs'])
     }
     return '<input type="text" name="json_key[%(fieldname)s]" value="%(key)s" %(key_attrs)s> <input type="text" name="json_value[%(fieldname)s]" value="%(value)s" %(val_attrs)s><br />' % ctx
Esempio n. 13
0
 def render_pair(self, key, value, name):
     ctx = {
         'key': key,
         'value': value,
         'fieldname': name,
         'key_attrs': flatatt(self.attrs['key_attrs']),
         'val_attrs': flatatt(self.attrs['val_attrs'])
     }
     return '<input type="text" name="json_key[%(fieldname)s]" value="%(key)s" %(key_attrs)s> <input type="text" name="json_value[%(fieldname)s]" value="%(value)s" %(val_attrs)s><br />' % ctx
Esempio n. 14
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ""
     final_attrs = self.build_attrs(attrs, type=self.input_type, placeholder=self.placeholder, name=name)
     if value != "":
         # Only add the 'value' attribute if a value is non-empty.
         final_attrs["value"] = force_unicode(self._format_value(value))
     if self.is_required:
         return mark_safe(u"<input%s required>" % flatatt(final_attrs))
     else:
         return mark_safe(u"<input%s>" % flatatt(final_attrs))
Esempio n. 15
0
    def render(self, name, value, attrs=None):
        """Renders this widget into an html string

        args:
        name  (str)  -- name of the field
        value (str)  -- a json string of a two-tuple list automatically passed in by django
        attrs (dict) -- automatically passed in by django (unused in this function)
        """

        if (not value) or value.strip() is '': value = '{"":""}'
        twotuple = json.loads(force_unicode(value))

        if isinstance(twotuple, dict):
            twotuple = [(
                k,
                v,
            ) for k, v in twotuple.iteritems()]
        if not twotuple:
            twotuple = [("", "")]

        ret = ''
        if value and len(value) > 0:
            for k, v in twotuple:
                ctx = {
                    'key': k,
                    'value': v,
                    'fieldname': name,
                    'key_attrs': flatatt(self.key_attrs),
                    'val_attrs': flatatt(self.val_attrs)
                }
                ret += """
                    <div class="form-group" id="">
                        <div class="col-md-4">
                            <input placeholder="Key" class="form-control" type="text" name="json_key[%(fieldname)s]" value="%(key)s" %(key_attrs)s>
                        </div>
                        <div class="col-md-1" style="font-size: 2em; text-align: center;">
                        =
                        </div>
                        <div class="col-md-5">
                            <input placeholder="Value"  class="form-control" type="text" name="json_value[%(fieldname)s]" value="%(value)s" %(val_attrs)s>
                        </div>
                        <div class="col-md-2 btn-group" role="group" aria-label="...">
                            <a class="btn btn-large btn-success">
                                <i class="glyphicon glyphicon-plus"></i>
                            </a>
                            <a class="btn btn-large btn-danger">
                                <i class="glyphicon glyphicon-minus"></i>
                            </a>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                    """ % ctx
        ret = '<span id="metadata_fields">' + ret + '</span>'
        return mark_safe(ret)
Esempio n. 16
0
 def render_pair(self, key, value, name):
     ctx = {
         "key": key,
         "value": value,
         "fieldname": name,
         "key_attrs": flatatt(self.attrs["key_attrs"]),
         "val_attrs": flatatt(self.attrs["val_attrs"]),
     }
     return (
         '<input type="text" name="json_key[%(fieldname)s]" value="%(key)s" %(key_attrs)s> <input type="text" name="json_value[%(fieldname)s]" value="%(value)s" %(val_attrs)s><br />'
         % ctx
     )
Esempio n. 17
0
def embed_flash(url,
                id,
                width,
                height,
                flashvars={},
                attributes={},
                version="10"):
    """Return markup for directly embedding flash into an HTML document."""

    #  Make the SWF play well with scripts and other page graphics
    params = {
        'allowscriptaccess': "always",
        'wmode': "transparent",
        'allowfullscreen': "true"
    }

    #  Build the markup for optional parameters
    object_params = "\n".join([
        u'<param name="%(name)s" value="%(value)s" />' % {
            'name': key,
            'value': value
        } for key, value in params.iteritems()
    ])

    markup = """
		<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
				id="%(id)s" width="%(width)d" height="%(height)d" %(attributes)s
				codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
			<param name="movie" value="%(url)s" />
			<param name="flashvars" value="%(flashvars)s" />
			%(object_params)s
			<embed src="%(url)s" width="%(width)d" height="%(height)d" name="%(id)s"
				%(embed_params)s %(attributes)s
				flashvars="%(flashvars)s"
				type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
			</embed>
		</object>
	""" % {
        'url': url,
        'id': id,
        'height': height,
        'width': width,
        'flashvars': re.sub(r'&', '&amp;', urllib.urlencode(flashvars)),
        'object_params': object_params,
        'embed_params': flatatt(params),
        'attributes': flatatt(attributes),
    }

    return mark_safe(markup)
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)

        if value:
            saidabtn = mark_safe(
                u'<input type=hidden %s value=%s /><input type=button name="btnfinger" value="Recapturar Digitais" onclick="document.getElementById(%s).value=registradigital();">'
                % (flatatt(final_attrs), value, "'id_Impressao'"))
        else:
            saidabtn = mark_safe(
                u'<input type=hidden %s value=%s /><input type=button name="btnfinger" value="Capturar Digitais" onclick="document.getElementById(%s).value=registradigital();">'
                % (flatatt(final_attrs), value, "'id_Impressao'"))

        return saidabtn
Esempio n. 19
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        final_attrs['class'] = 'tinymce'
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"
        mce_config = self.get_mce_config(final_attrs)
        mce_json = self.get_mce_json(mce_config)
        if tinymce.settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }
            final_attrs['data-mce-gz-conf'] = json.dumps(compressor_config)
        html = [
            '<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))
        ]
        html.append(
            '<script type="text/javascript" defer>tinyMCE.init(%s);</script>' %
            mce_json)
        if 'file_picker_callback' in mce_json:
            mce_json = json.loads(mce_json)
            html[1] = html[1].replace(
                '"' + mce_json['file_picker_callback'] + '"',
                mce_json['file_picker_callback'].replace('"', ''))

        print mce_json
        print '\n'.join(html)
        return mark_safe('\n'.join(html))
Esempio n. 20
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] = final_attrs['class'] + ' cleditor'
        else:
            final_attrs['class'] = 'cleditor'

        a = mark_safe(u'''
        <textarea%s>%s</textarea>

        <script type="text/javascript">
            var %s_cleditor;
            $(document).ready(function() {
                $.cleditor.defaultOptions.controls = "%s";
                $.cleditor.defaultOptions.width = %s;
                $.cleditor.defaultOptions.height = %s;
                %s_cleditor = $("#%s.cleditor").cleditor();
                $('#upload form').ajaxForm({ dataType : 'json', success : selectSize, beforeSubmit: loadingForm});
            });
        </script>''' % (flatatt(final_attrs),
                        conditional_escape(force_unicode(value)),
                        final_attrs['id'],
                        self.attrs['controls'],
                        self.attrs['width'],
                        self.attrs['height'],
                        final_attrs['id'],
                        final_attrs['id']))
        return a
Esempio n. 21
0
    def render(self, name, value, attrs=None):

        # ng-model='checkin' is-open="opened" ng-focus="opened=true" datepicker-popup

        # or

        # <p class="input-group">
        #   <input type="text" class="form-control" ng-model='checkin' is-open="opened" ng-focus="opened=true" datepicker-popup  />
        #   <span class="input-group-btn">
        #     <button type="button" class="btn btn-default" ng-click="opened=true;$event.stopPropagation()"><i class="glyphicon glyphicon-calendar"></i></button>
        #   </span>
        # </p>

        attrs['ng-model'] = attrs['id']
        attrs['is-open'] = "%s_opened" % attrs['id']
        attrs['ng-focus'] = "%s_opened=true" % attrs['id']

        if value is None:
            value = ''

        attrs['ng-init'] = "%s='%s'" % (attrs['ng-model'],value)

        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)

        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(self._format_value(value))

        # print final_attrs
        # print flatatt(final_attrs)
        # print format_html('<input{0} datepicker-popup/>', flatatt(final_attrs))


        return format_html('<input{0} datepicker-popup/>', flatatt(final_attrs))
Esempio n. 22
0
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     if 'class' not in attrs:
         attrs['class'] = ""
     attrs['class'] += " wmd-input"
     final_attrs = self.build_attrs(attrs, name=name)
     html = """
         <div class="wmd-wrapper">
             <div class="wmd-panel">
             <div id="%(id)s_wmd_button_bar"></div>
             <textarea%(attrs)s>%(body)s</textarea>
             </div>
             <div id="%(id)s_wmd_preview" class="wmd-panel wmd-preview"></div>
         </div>
         <script type="text/javascript">
             $(document).ready(function() {
             (function () {
                 var converter = Markdown.getSanitizingConverter();
                 selectors = {
                     input : "%(id)s",
                     button : "%(id)s_wmd_button_bar", 
                     preview : "%(id)s_wmd_preview",
                 }
                 var editor = new Markdown.Editor(converter, selectors);
                 editor.run();
             })();
             });
         </script>
         """ % {
         'attrs': flatatt(final_attrs),
         'body': conditional_escape(force_unicode(value)),
         'id': attrs['id'],
     }
     return mark_safe(html)
Esempio n. 23
0
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     if 'class' not in attrs:
         attrs['class'] = ""
     attrs['class'] += " wmd-input"
     final_attrs = self.build_attrs(attrs, name=name)
     html = """
         <div class="wmd-wrapper">
             <div class="wmd-panel">
             <div id="%(id)s_wmd_button_bar"></div>
             <textarea%(attrs)s>%(body)s</textarea>
             </div>
             <div id="%(id)s_wmd_preview" class="wmd-panel wmd-preview"></div>
         </div>
         <script type="text/javascript">
             $(document).ready(function() {
             (function () {
                 var converter = Markdown.getSanitizingConverter();
                 selectors = {
                     input : "%(id)s",
                     button : "%(id)s_wmd_button_bar", 
                     preview : "%(id)s_wmd_preview",
                 }
                 var editor = new Markdown.Editor(converter, selectors);
                 editor.run();
             })();
             });
         </script>
         """ % {
             'attrs' : flatatt(final_attrs),
             'body' : conditional_escape(force_unicode(value)),
             'id' : attrs['id'],
         }
     return mark_safe(html)
Esempio n. 24
0
 def render(self, name, value, attrs=None):
     table_sections = table_sections_re.search(value).groups()
     output = []
     heads = []
     current_row = []
     first_row = True
     first_head_id = None
     prefix = "id_%s-%%s-" % self.formset.prefix
     for row, head, item in table_row_re.findall(table_sections[1]):
         if first_row:
             head_groups = label_re.search(head).groups()
             if first_head_id == head_groups[1]:
                 first_row = False
                 output.append(current_row)
                 current_row = []
             else:
                 heads.append("%s%s%s" % (head_groups[0], head_groups[2], head_groups[3]))
                 if first_head_id is None:
                     first_head_id = head_groups[1].replace("-0-", "-1-")
         current_row.append(item)
         if not first_row and len(current_row) >= len(heads):
             output.append(current_row)
             current_row = []
     if len(current_row) != 0:
         raise Exception("Unbalanced render")
     return mark_safe(
         u"%s<table%s><tr>%s</tr><tr>%s</tr></table>%s"
         % (
             table_sections[0],
             flatatt(attrs),
             u"".join(heads),
             u"</tr><tr>".join((u"".join(x) for x in output)),
             table_sections[2],
         )
     )
Esempio n. 25
0
    def render(self, name, value=None, attrs={}):
        final_attrs = self.build_attrs(attrs, name=name)

        # Handles different types of choices
        if isinstance(self.choices, list):
            source = simplejson.dumps(self.choices)
        elif isinstance(self.choices, str):
            source = "'{0}'".format(escape(self.choices))
        elif isinstance(self.choices, tuple):  # assumes tuple will be 2-item choice tuples (as in the docs)
            try:
                ## This sets the displayed values
                # If you have (for example) "fruit" tuples like (('apples', 'apples'),), then you can
                # just use item[0] for the "label"
                # The below set up is useful for displaying the human-readable format, and inserting
                # the value that will go into the database. For instance, (('FL', 'Florida'),) will
                # display "Florida" but insert "FL" into the field.
                source = simplejson.dumps([{"label": "{0}".format(item[1]), "value": "{0}".format(item[0])} for item in self.choices])
            except IndexError:
                raise ValueError("choices tuple is not valid")
        else:
            raise ValueError("choices type is not valid")

        options = ''
        if self.options:
            options += ",{0}".format(self.options)  # for passing add'l autocomplete options

        if value:
            value = force_unicode(value)
            final_attrs['value'] = escape(value)
        if not self.attrs.has_key('id'):
            final_attrs['id'] = 'id_{0}'.format(name)
        return mark_safe(u'''<input type="text" name="{0}" id="{1}" {2}>
                <script type="text/javascript">
                    $('#{1}').autocomplete({{source:{3}{4}}});
                </script>'''.format(name, flatatt(final_attrs), final_attrs['id'], source, options))
Esempio n. 26
0
    def render(self, name, value, attrs=None):
        from django.template import Context, Template
        from django.template.context import Context
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_unicode(self._format_value(value))
        final_attrs['size'] = 10
        t = Template(u"""
<input{{ attrs|safe }} />
{% if instance %}
    <a href="{{ changelist_url|safe }}?t=id" class="related-lookup" id="lookup_{{ id|safe }}" onclick="return showRelatedObjectLookupPopup(this);">
        <img src="/media/admin/img/admin/selector-search.gif" width="16" height="16" alt="Lookup" />
    </a>
    <strong><a href="{{ url|safe }}" target="_blank">{{ instance|safe }}</a></strong>
{% endif %}
        """)
        c = Context(dict(
            id=final_attrs['id'],
            attrs=flatatt(final_attrs),
            raw_value=self._raw_value,
            url=get_admin_change_url(self._instance),
            changelist_url=get_admin_changelist_url(self._model_class),
            instance=self._instance))
        return  mark_safe(t.render(c))
Esempio n. 27
0
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     value = smart_unicode(value)
     final_attrs = self.build_attrs(attrs, name=name)
     id = attrs['id']
     
     return str(u"""<input %s/> <span>Нэрийг нь бичнэ үү</span>
                     <script type="text/javascript">
                          //<!CDATA[
                          
                             jQuery("#%s").autocomplete('%s', {
                                     width: 250,
                                     multiple: false,
                                     matchContains: false,
                                     formatItem: function(row) {
                                            return row[0] + " (<strong>id: " + row[1] + "</strong>)";
                                     },
                                     formatResult: function (row) {
                                         return row[0].replace(/(<.+?>)/gi, '');
                                     }
                                 });
                                                      
                          //]>
                     </script>
                          """
                       % (flatatt(final_attrs) ,  id, self.remote_url))
Esempio n. 28
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     value = force_text(value)
     final_attrs = self.build_attrs(attrs)
     final_attrs['name'] = name
     if final_attrs.get('class', None) is None:
         final_attrs['class'] = 'tinymce'
     else:
         final_attrs['class'] = ' '.join(final_attrs['class'].split(' ') + ['tinymce'])
     assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"
     mce_config = self.get_mce_config(final_attrs)
     mce_json = self.get_mce_json(mce_config)
     if tinymce.settings.USE_COMPRESSOR:
         compressor_config = {
             'plugins': mce_config.get('plugins', ''),
             'themes': mce_config.get('theme', 'advanced'),
             'languages': mce_config.get('language', ''),
             'diskcache': True,
             'debug': False,
         }
         final_attrs['data-mce-gz-conf'] = json.dumps(compressor_config)
     final_attrs['data-mce-conf'] = mce_json
     html = ['<textarea{!s}>{!s}</textarea>'.format(flatatt(final_attrs), escape(value))]
     return mark_safe('\n'.join(html))
Esempio n. 29
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        final_attrs['class'] = 'tinymce'
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"
        mce_config = self.get_mce_config(final_attrs)
        mce_json = self.get_mce_json(mce_config)
        if tinymce.settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }
            final_attrs['data-mce-gz-conf'] = json.dumps(compressor_config)
        html = ['<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))]
        html.append('<script type="text/javascript" defer>tinyMCE.init(%s);</script>' % mce_json)
        if 'file_picker_callback' in mce_json:
            mce_json = json.loads(mce_json)
            html[1] = html[1].replace('"'+mce_json['file_picker_callback']+'"',mce_json['file_picker_callback'].replace('"',''))

        print mce_json
        print '\n'.join(html)
        return mark_safe('\n'.join(html))
Esempio n. 30
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)
        # textarea_id = self.settings['id'] = "id_%s" % name
        textarea_id = final_attrs['id']

        # try:
        #    js_url = settings.EDITAREA_JS_FOLDER
        # except AttributeError:
        #    js_url = settings.MEDIA_URL + "js/"

        try:
            default_editarea_args =\
                settings.EDITAREA_DEFAULT_ARGS(textarea_id)
        except AttributeError:
            default_editarea_args = '{id : "' + textarea_id + '" }'

        editarea_args = default_editarea_args
        init_script = ''
        if editarea_args:
            init_script =\
                "<script>"\
                "editAreaLoader.init("+editarea_args+");alert("+name+")"\
                "</script>"

        # <script src="%seditarea/edit_area_loader.js"></script>
        return mark_safe(u"""
        <textarea %s>%s</textarea>
        """ % (flatatt(final_attrs),
                   escape(value))
        + init_script
        )
Esempio n. 31
0
    def render(self, name, value, attrs=None, choices=()):
        all_choices = list(chain(self.choices, choices))

        if len(all_choices) <= 1:
            return ''

        if value is None:
            value = all_choices[0][0]

        _id = attrs.pop('id')
        final_attrs = flatatt(self.build_attrs(attrs))
        value_label = self.get_option_label(value, choices=choices)

        options = super().render(name,
                                 value,
                                 attrs={
                                     'class': 'dropdown-menu',
                                     'aria-labelledby': _id,
                                 },
                                 choices=choices)

        return render_to_string(
            self.template, {
                'options': options,
                'id': _id,
                'attrs': final_attrs,
                'value_label': value_label,
                'label': self.label,
                'right': self.right,
            })
    def render(self, name, value, attrs=None, renderer=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(self._format_value(value))
        final_attrs['size'] = 10
        final_attrs['type'] = 'text'
        final_attrs['name'] = name
        t = Template(u"""
{% load staticfiles %}
<input{{ attrs|safe }} />
{% if instance %}
    <a href="{{ changelist_url|safe }}?t=id" class="related-lookup" id="lookup_{{ id|safe }}" onclick="return showRelatedObjectLookupPopup(this);">
        <img src="{% static 'admin/img/selector-search.gif' %}" width="16" height="16" alt="Lookup" />
    </a>
    <strong><a href="{{ url|safe }}" target="_blank">{{ instance|safe }}</a></strong>
{% endif %}
        """)
        c = Context(dict(
            id=final_attrs['id'],
            attrs=flatatt(final_attrs),
            raw_value=self._raw_value,
            url=utils.get_admin_change_url(self._instance),
            changelist_url=utils.get_admin_changelist_url(self._model_class),
            instance=self._instance,
        ))
        return mark_safe(t.render(c))
Esempio n. 33
0
    def render(self, name, value, attrs=None):
        """Render TinyMCE widget as HTML.
    """

        from soc.logic.models.user import logic as user_logic

        user = user_logic.getCurrentUser()

        if user and user.disable_tinymce:
            return super(FullTinyMCE, self).render(name, value, attrs)

        if value is None:
            value = ""
        value = encoding.smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)

        self.mce_settings["elements"] = "id_%s" % name

        # convert mce_settings from dict to JSON
        mce_json = simplejson.JSONEncoder().encode(self.mce_settings)

        return safestring.mark_safe(
            self.TINY_MCE_HTML_FMT
            % {"attrs": widgets.flatatt(final_attrs), "value": html.escape(value), "settings_json": mce_json}
        )
Esempio n. 34
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     value = force_text(value)
     final_attrs = self.build_attrs(attrs)
     final_attrs['name'] = name
     if final_attrs.get('class', None) is None:
         final_attrs['class'] = 'tinymce'
     else:
         final_attrs['class'] = ' '.join(final_attrs['class'].split(' ') +
                                         ['tinymce'])
     assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"
     mce_config = self.get_mce_config(final_attrs)
     mce_json = self.get_mce_json(mce_config)
     if tinymce.settings.USE_COMPRESSOR:
         compressor_config = {
             'plugins': mce_config.get('plugins', ''),
             'themes': mce_config.get('theme', 'advanced'),
             'languages': mce_config.get('language', ''),
             'diskcache': True,
             'debug': False,
         }
         final_attrs['data-mce-gz-conf'] = json.dumps(compressor_config)
     final_attrs['data-mce-conf'] = mce_json
     html = [
         '<textarea{!s}>{!s}</textarea>'.format(flatatt(final_attrs),
                                                escape(value))
     ]
     return mark_safe('\n'.join(html))
Esempio n. 35
0
 def render(self, name, value, attrs=None):
     table_sections = table_sections_re.search(value).groups()
     output = []
     heads = []
     current_row = []
     first_row = True
     first_head_id = None
     prefix = 'id_%s-%%s-' % self.formset.prefix
     for row, head, item in table_row_re.findall(table_sections[1]):
         if first_row:
             head_groups = label_re.search(head).groups()
             if first_head_id == head_groups[1]:
                 first_row = False
                 output.append(current_row)
                 current_row = []
             else:
                 heads.append(
                     '%s%s%s' %
                     (head_groups[0], head_groups[2], head_groups[3]))
                 if first_head_id is None:
                     first_head_id = head_groups[1].replace('-0-', '-1-')
         current_row.append(item)
         if not first_row and len(current_row) >= len(heads):
             output.append(current_row)
             current_row = []
     if len(current_row) != 0:
         raise Exception('Unbalanced render')
     return mark_safe(u'%s<table%s><tr>%s</tr><tr>%s</tr></table>%s' %
                      (table_sections[0], flatatt(attrs), u''.join(heads),
                       u'</tr><tr>'.join(
                           (u''.join(x)
                            for x in output)), table_sections[2]))
Esempio n. 36
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)
        textarea_id = self.settings['id'] = "id_{0}".format(name)

        try:
            js_url = settings.EDITAREA_JS_FOLDER
        except AttributeError:
            js_url = settings.MEDIA_URL + "js/"

        try:
            default_editarea_args =\
                settings.EDITAREA_DEFAULT_ARGS(textarea_id)
        except AttributeError:
            default_editarea_args = '{id : "' + textarea_id + '" }'

        editarea_args = default_editarea_args
        init_script = '' if not editarea_args else\
        "<script>"\
            "editAreaLoader.init("+editarea_args+");"\
        "</script>"

        return mark_safe(u"""
        <textarea{final_attrs}>{value}</textarea>
        <script src="{js_url}editarea/edit_area_loader.js"></script>
        """.format(final_attrs=flatatt(final_attrs),
                   value=escape(value),
                   js_url=js_url)
        + init_script
        )
Esempio n. 37
0
    def render(self, name, value, attrs=None, renderer=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(self._format_value(value))
        final_attrs['size'] = 10
        final_attrs['type'] = 'text'
        final_attrs['name'] = name
        t = Template(u"""
{% load staticfiles %}
<input{{ attrs|safe }} />
{% if instance %}
    <a href="{{ changelist_url|safe }}?t=id" class="related-lookup" id="lookup_{{ id|safe }}" onclick="return showRelatedObjectLookupPopup(this);">
        <img src="{% static 'admin/img/selector-search.gif' %}" width="16" height="16" alt="Lookup" />
    </a>
    <strong><a href="{{ url|safe }}" target="_blank">{{ instance|safe }}</a></strong>
{% endif %}
        """)
        c = Context(dict(
            id=final_attrs['id'],
            attrs=flatatt(final_attrs),
            raw_value=self._raw_value,
            url=utils.get_admin_change_url(self._instance),
            changelist_url=utils.get_admin_changelist_url(self._model_class),
            instance=self._instance,
        ))
        return mark_safe(t.render(c))
Esempio n. 38
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)
        # textarea_id = self.settings['id'] = "id_%s" % name
        textarea_id = final_attrs['id']

        # try:
        #    js_url = settings.EDITAREA_JS_FOLDER
        # except AttributeError:
        #    js_url = settings.MEDIA_URL + "js/"

        try:
            default_editarea_args =\
                settings.EDITAREA_DEFAULT_ARGS(textarea_id)
        except AttributeError:
            default_editarea_args = '{id : "' + textarea_id + '" }'

        editarea_args = default_editarea_args
        init_script = ''
        if editarea_args:
            init_script =\
                "<script>"\
                "editAreaLoader.init("+editarea_args+");alert("+name+")"\
                "</script>"

        # <script src="%seditarea/edit_area_loader.js"></script>
        return mark_safe(u"""
        <textarea %s>%s</textarea>
        """ % (flatatt(final_attrs), escape(value)) + init_script)
Esempio n. 39
0
    def render(self, name, value, attrs=None):
        configuration =  copy(self.configuration)

        if 'prePopulate' not in configuration:
            configuration['prePopulate'] = []

        if value is not None:
            if self.event == None:
                configuration['prePopulate'].extend([{'id': v, 'name': label} for v, label in self.choices])
            else:
                for v, label in self.choices:
                    if User.objects.get(pk=v).participation_set.get(event=self.event, role=self.role).attending == "null":
                        src = "/static/images/yellow_circle.png"
                    if User.objects.get(pk=v).participation_set.get(event=self.event, role=self.role).attending == "true":
                        src = "/static/images/tick.png"                    
                    if User.objects.get(pk=v).participation_set.get(event=self.event, role=self.role).attending == "false":
                        src = "/static/images/cross.png"

                    status = "<img style='float:right;height:9px; margin-right:15px' src='%s'>" % src
                    configuration['prePopulate'].extend([{'id': v, 'name': label, 'status': status}])


        attrs['id'] = attrs['id'].replace(" ", "")
        final_attrs = self.build_attrs(attrs, name=name)
        context = {
            'id': final_attrs.get('id', '_'),
            'attrs': flatatt(final_attrs),
            'json_source': self.json_source,
            'configuration': json.dumps(configuration)[1:-1],
            'event': self.event,
        }
        return mark_safe(self.template % context)
Esempio n. 40
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     if 'class' not in attrs:
         attrs['class'] = ""
     attrs['class'] += " wmd-input"
     final_attrs = self.build_attrs(attrs, name=name)
     html = """
         <div class="wmd-wrapper">
             <div class="wmd-panel">
             <div id="%(id)s_wmd_button_bar"></div>
             <textarea%(attrs)s>%(body)s</textarea>
             </div>
             <div id="%(id)s_wmd_preview" class="wmd-panel wmd-preview"></div>
         </div>
         <script type="text/javascript">
             (function () {
                 var converter = Markdown.getSanitizingConverter();
                 selectors = {
                     input : "%(id)s",
                     button : "%(id)s_wmd_button_bar",
                     preview : "%(id)s_wmd_preview",
                 }
                 var editor = new Markdown.Editor(converter, "", selectors);
                 var postfix = "";
                 somesquares.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\\\\\\\(","\\\\\\\\)"]]);
                 editor.run();
             })();
         </script>
         """ % {
             'attrs': flatatt(final_attrs),
             'body': conditional_escape(force_unicode(value)),
             'id': final_attrs['id'],
         }
     return mark_safe(html)
	def render(self, name, value, attrs=None, choices=()):
		if value is None: value = ''
		highlight_name = name+self.hightlight_suffix
		highlight_vals = []
		output = []
		for val,label in self.highlighted:
			highlight_vals.append(val)
			output.append(self.render_radio_input(highlight_name,val,label,value,attrs))
		for val,label in chain(self.choices,choices):
			if val != '' and val not in highlight_vals and val == value:
				highlight_vals.append(val)
				output.append(self.render_radio_input(highlight_name,val,label,value,attrs))
		final_attrs = self.build_attrs(attrs, name=name)
		
		other_attrs = attrs.copy()
		for val,label in choices:
			if val == value:
				other_attrs['checked'] = 'checked'
		other_label = 'Other'
		if 'other_label' in attrs:
			other_label = attrs['other_label']
		output.append(self.render_radio_input(highlight_name,self.other_value,other_label,value,other_attrs))
		output.append(u'<select%s>' % flatatt(final_attrs))
		_choices = []
		if len(choices) < 1:
			choices = self.choices
		for val,label in choices:
			if val not in highlight_vals:
				_choices.append((val,label))
		self.choices = _choices # i don't love this line
		options = self.render_options([], [value])
		if options:
			output.append(options)
		output.append(u'</select>')
		return mark_safe(u'\n'.join(output))
Esempio n. 42
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)

        self_config = DEFAULT_CONFIG[self.config_name].copy()
        configs = getattr(settings, 'CKEDITOR_CONFIGS', None)
        if configs != None:
            if isinstance(configs, dict):
                # Make sure the config_name exists.
                if configs.has_key(self.config_name):
                    config = configs[self.config_name].copy()
                    # Make sure the configuration is a dictionary.
                    if not isinstance(config, dict):
                        raise ImproperlyConfigured('CKEDITOR_CONFIGS["%s"] setting must be a dictionary type.' % self.config_name)
                    self_config.update(config)
                #else:
                    #raise ImproperlyConfigured("No configuration named '%s' found in your CKEDITOR_CONFIGS setting." % self.config_name)
            else:
                raise ImproperlyConfigured('CKEDITOR_CONFIGS setting must be a dictionary type.')

        ck_json = JSONEncoder().encode(self_config)
        return mark_safe(u'<textarea%s>%s</textarea> <script type="text/javascript" charset="utf-8"> \
            CKEDITOR.replace( "%s", %s); \
        </script>' % (flatatt(final_attrs), escape(value),'id_'+name,ck_json)
        )
Esempio n. 43
0
 def render(self, name, value, attrs=None):
     table_sections = table_sections_re.search(value).groups()
     output = []
     heads = []
     current_row = []
     first_row = True
     first_head_id = None
     prefix = 'id_%s-%%s-' % self.formset.prefix
     for row, head, item in table_row_re.findall(table_sections[1]):
         if first_row:
             head_groups = label_re.search(head).groups()
             if first_head_id == head_groups[1]:
                 first_row = False
                 output.append(current_row)
                 current_row = []
             else:
                 heads.append('%s%s%s' % (head_groups[0], head_groups[2], head_groups[3]))
                 if first_head_id is None:
                     first_head_id = head_groups[1].replace('-0-','-1-')
         current_row.append(item)
         if not first_row and len(current_row) >= len(heads):
             output.append(current_row)
             current_row = []
     if len(current_row) != 0:
         raise Exception('Unbalanced render')
     def last_first(tuple):
         return tuple[-1:] + tuple[:-1]
     return mark_safe(u'%s<table%s><tr>%s</tr><tr>%s</tr></table>%s'%(
         table_sections[0],
         flatatt(attrs),
         u''.join(last_first(heads)),
         u'</tr><tr>'.join((u''.join(last_first(x)) for x in output)), 
         table_sections[2]))
Esempio n. 44
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"

        mce_config = tinymce_settings.DEFAULT_CONFIG.copy()
        mce_config.update(get_language_config(self.content_language))
        if tinymce_settings.USE_FILEBROWSER:
            mce_config['file_browser_callback'] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        mce_config['mode'] = 'exact'
        mce_config['elements'] = final_attrs['id']
        mce_config['strict_loading_mode'] = 1
        mce_json = simplejson.dumps(mce_config)

        html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))]
        if tinymce_settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }
            compressor_json = simplejson.dumps(compressor_config)
            html.append(u'<script type="text/javascript">tinyMCE_GZ.init(%s)</script>' % compressor_json)
        html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json)

        return mark_safe(u'\n'.join(html))
Esempio n. 45
0
 def tag(self):
     if 'id' in self.attrs:
         self.attrs['id'] = 'rating_%s' % self.index
     final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value)
     if self.is_checked():
         final_attrs['checked'] = 'checked'
     return mark_safe(u'<input%s>' % flatatt(final_attrs))
Esempio n. 46
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ""
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs["name"] = name
        assert "id" in final_attrs, "TinyMCE widget attributes must contain 'id'"

        mce_config = tinymce.settings.DEFAULT_CONFIG.copy()
        mce_config.update(get_language_config(self.content_language))
        if tinymce.settings.USE_FILEBROWSER:
            mce_config["file_browser_callback"] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        mce_config["mode"] = "exact"
        mce_config["elements"] = final_attrs["id"]
        mce_config["strict_loading_mode"] = 1
        mce_json = simplejson.dumps(mce_config)

        html = [u"<textarea%s>%s</textarea>" % (flatatt(final_attrs), escape(value))]
        if tinymce.settings.USE_COMPRESSOR:
            compressor_config = {
                "plugins": mce_config.get("plugins", ""),
                "themes": mce_config.get("theme", "advanced"),
                "languages": mce_config.get("language", ""),
                "diskcache": True,
                "debug": False,
            }
            compressor_json = simplejson.dumps(compressor_config)
            html.append(u'<script type="text/javascript">tinyMCE_GZ.init(%s)</script>' % compressor_json)
        html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json)

        return mark_safe(u"\n".join(html))
Esempio n. 47
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"

        mce_config = tinymce.settings.DEFAULT_CONFIG.copy()
        mce_config.update(get_language_config(self.content_language))
        if tinymce.settings.USE_FILEBROWSER:
            mce_config['file_browser_callback'] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        mce_config['mode'] = 'exact'
        mce_config['elements'] = final_attrs['id']
        mce_config['strict_loading_mode'] = 1
        mce_json = simplejson.dumps(mce_config)

        html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))]
        if tinymce.settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }
            compressor_json = simplejson.dumps(compressor_config)
            html.append(u'<script type="text/javascript">tinyMCE_GZ.init(%s)</script>' % compressor_json)
        html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json)

        return mark_safe(u'\n'.join(html))
Esempio n. 48
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)
        textarea_id = self.settings['id'] = "id_{0}".format(name)

        try:
            js_url = settings.EDITAREA_JS_FOLDER
        except AttributeError:
            js_url = settings.MEDIA_URL + "js/"

        try:
            default_editarea_args =\
                settings.EDITAREA_DEFAULT_ARGS(textarea_id)
        except AttributeError:
            default_editarea_args = '{id : "' + textarea_id + '" }'

        editarea_args = default_editarea_args
        init_script = '' if not editarea_args else\
        "<script>"\
            "editAreaLoader.init("+editarea_args+");"\
        "</script>"

        return mark_safe(u"""
        <textarea{final_attrs}>{value}</textarea>
        <script src="{js_url}editarea/edit_area_loader.js"></script>
        """.format(final_attrs=flatatt(final_attrs),
                   value=escape(value),
                   js_url=js_url) + init_script)
 def render(self, name, value, attrs=None):
     if value is None:
         value = []
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     if value != '':
         # Only add the 'value' attribute if a value is non-empty.
         final_attrs['value'] = force_unicode(self._format_value(value))
     return mark_safe(u'<input%s />' % flatatt(final_attrs))
Esempio n. 50
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     final_attrs = self.build_attrs(attrs, type='hidden', name=name)
     if value != '':
         final_attrs['value'] = widgets.force_text(value)
     return widgets.format_html('<input{0} />{1}',
                                widgets.flatatt(final_attrs),
                                value)
Esempio n. 51
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     value = smart_text(value)
     final_attrs = self.build_attrs(attrs)
     final_attrs['name'] = name
     mce_config = self.profile.copy()
     mce_config.update(self.mce_attrs)
     if mce_config.get('inline', False):
         html = '<div{0}>{1}</div>\n'.format(flatatt(final_attrs),
                                             escape(value))
     else:
         html = '<textarea{0}>{1}</textarea>\n'.format(
             flatatt(final_attrs), escape(value))
     html += '<script type="text/javascript">{0}</script>'.format(
         render_tinymce_init_js(mce_config, mce_settings.CALLBACKS.copy(),
                                final_attrs['id']))
     return mark_safe(html)
Esempio n. 52
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"

        mce_config = tinymce.settings.DEFAULT_CONFIG.copy()
        mce_config.update(get_language_config(self.content_language))
        if tinymce.settings.USE_FILEBROWSER:
            mce_config['file_browser_callback'] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        mce_config['mode'] = 'exact'
        mce_config['elements'] = final_attrs['id']
        mce_config['strict_loading_mode'] = 1
        mce_json = simplejson.dumps(mce_config)
        # Patch for inlines
        pos = final_attrs['id'].find('__prefix__')
        if pos != -1:
            mce_json = mce_json.replace(u'"%s"' % final_attrs['id'],
                                        u'elements')
# EOP
        html = [
            u'<textarea%s>%s</textarea>' %
            (flatatt(final_attrs), escape(value))
        ]
        if tinymce.settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }
            compressor_json = simplejson.dumps(compressor_config)
            html.append(
                u'<script type="text/javascript">tinyMCE_GZ.init(%s)</script>'
                % compressor_json)
# Patch for inlines
        if pos != -1:
            html.append(u'''<script type="text/javascript">
setTimeout(function () {
    var elements = '%s'.replace(/__prefix__/, parseInt(document.getElementById('%sTOTAL_FORMS').value) - 1);
    if (document.getElementById(elements)) {
        tinymce.init(%s);
    }
}, 0);
</script>''' % (final_attrs['id'], final_attrs['id'][0:pos], mce_json))
        else:
            html.append(
                u'<script type="text/javascript">tinyMCE.init(%s)</script>' %
                mce_json)


# EOP

        return mark_safe(u'\n'.join(html))
Esempio n. 53
0
def render_tag(attrs=None, content=None):
    """
    Render a HTML tag
    """
    builder = '<pre><code{attrs}>{content}</code></pre>'
    return builder.format(
        attrs=flatatt(attrs) if attrs else '',
        content=escape(text_value(content)),
    )
Esempio n. 54
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"
        mce_config = cms.plugins.text.settings.TINYMCE_CONFIG.copy()
        mce_config.update(get_language_config(self.content_language))
        if tinymce.settings.USE_FILEBROWSER:
            mce_config['file_browser_callback'] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        mce_config['mode'] = 'exact'
        mce_config['elements'] = final_attrs['id']
        mce_config['strict_loading_mode'] = 1
        plugins = mce_config.get("plugins", "")
        if len(plugins):
            plugins += ","
        plugins += "-cmsplugins"
        mce_config['plugins'] = plugins
        if mce_config['theme'] == "simple":
            mce_config['theme'] = "advanced"
        # Add cmsplugin to first toolbar, if not already present
        all_tools = []
        idx = 0
        while True:
            idx += 1
            buttons = mce_config.get('theme_advanced_buttons%d' % (idx, ),
                                     None)
            if buttons is None:
                break
            all_tools.extend(buttons.split(','))
        if 'cmsplugins' not in all_tools and 'cmspluginsedit' not in all_tools:
            mce_config[
                'theme_advanced_buttons1_add_before'] = "cmsplugins,cmspluginsedit"

        json = simplejson.dumps(mce_config)
        html = [
            u'<textarea%s>%s</textarea>' %
            (flatatt(final_attrs), escape(value))
        ]
        if tinymce.settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }
            c_json = simplejson.dumps(compressor_config)
            html.append(
                u'<script type="text/javascript">//<![CDATA[\ntinyMCE_GZ.init(%s);\n//]]></script>'
                % (c_json))
        html.append(
            u'<script type="text/javascript">//<![CDATA[\n%s;\ntinyMCE.init(%s);\n//]]></script>'
            % (self.render_additions(name, value, attrs), json))
        return mark_safe(u'\n'.join(html))
Esempio n. 55
0
 def render(self, name, value, attrs=None):
     value = value or u''
     value = force_unicode(value)
     final_attrs = self.build_attrs(attrs)
     final_attrs['name'] = name
     config = self.get_config(name)
     html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))]
     html.append(u'<input type="hidden" name="%(name)s_img" id="%(name)s_img">' % {'name': name})
     html.append(config)
     return mark_safe(u'\n'.join(html))
Esempio n. 56
0
    def render(self, name, value, attrs=None):
        value = smart_unicode(value or u'')
        final_attrs = self.build_attrs(attrs, name=name)

        if 'class' in final_attrs:
            final_attrs['class'] += ' cp-wysiwyg-widget'
        else:
            final_attrs['class'] = 'cp-wysiwyg-widget'

        return mark_safe(u'<textarea{0}>{1}</textarea>'.format(flatatt(final_attrs), escape(value)))
Esempio n. 57
0
def render_icon(icon, title=''):
    """
    Render a Bootstrap glyphicon icon
    """
    attrs = {
        'class': 'glyphicon glyphicon-{icon}'.format(icon=icon),
    }
    if title:
        attrs['title'] = title
    return '<span{attrs}></span>'.format(attrs=flatatt(attrs))
Esempio n. 58
0
def render_label(content, label_for=None, label_class=None, label_title=''):
    attrs = {}
    if label_for:
        attrs['for'] = label_for
    if label_class:
        attrs['class'] = label_class
    if label_title:
        attrs['title'] = label_title
    return '<label{attrs}>{content}</label>'.format(attrs=flatatt(attrs),
                                                    content=content)
Esempio n. 59
0
 def render(self, name, value, attrs=None, choices=()):
     if value is None: value = []
     final_attrs = self.build_attrs(attrs, name=name)
     output = [u'<select %s>' % flatatt(final_attrs)
               ]  # NOTE removed the multiple attribute
     options = self.render_options(choices, value)
     if options:
         output.append(options)
     output.append('</select>')
     return mark_safe(u'\n'.join(output))