コード例 #1
0
ファイル: admin.py プロジェクト: conrado/django-cms
 def insert_stack(self, request, placeholder_id):
     placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
     form = StackInsertionForm(initial={"language_code": request.GET.get("language_code", "")})
     if request.method == "POST":
         form = StackInsertionForm(data=request.POST)
         if form.is_valid():
             context = {"CMS_MEDIA_URL": get_cms_setting("MEDIA_URL"), "is_popup": True, "cancel": False}
             if form.cleaned_data["insertion_type"] == StackInsertionForm.INSERT_LINK:
                 cms_plugin = add_plugin(
                     placeholder, StackPlugin, form.cleaned_data["language_code"], stack=form.cleaned_data["stack"]
                 )
                 context.update(
                     {
                         "plugin": cms_plugin,
                         "type": cms_plugin.get_plugin_name(),
                         "plugin_id": cms_plugin.pk,
                         "icon": force_escape(escapejs(cms_plugin.get_instance_icon_src())),
                         "alt": force_escape(escapejs(cms_plugin.get_instance_icon_alt())),
                     }
                 )
             else:
                 plugin_ziplist = copy_plugins_to(
                     list(form.cleaned_data["stack"].content.get_plugins()), placeholder
                 )
                 # TODO: once we actually use the plugin context in the frontend, we have to support multiple plugins
             return TemplateResponse(request, "admin/cms/page/plugin/confirm_form.html", context)
     return TemplateResponse(request, "admin/stacks/insert_stack.html", {"form": form})
コード例 #2
0
 def render_item(self, results, label, o):
     if isinstance(o, BaseForm):
         self.render_row(results, label, self.render_explanation(o))
     elif isinstance(o, tuple):
         if len(o) < 10:
             if len(o) == 0:
                 self.render_row(results, label, "Empty tuple")
                 return ""
             self.render_row(results, label, force_escape("tuple %s:%s") + ",".join([(i,self.render_explanation(val)) 
                                             for (i,val) in enumerate(o)]))
         else:
             self.render_row(results, label, "Long tuple-- %s items -- e.g. %s.0=>%s " % (len(o), force_escape(label), self.render_explanation(o[0])))
     elif isinstance(o, (set, list, QuerySet)) or (is_iterable(o) and not isinstance(o, basestring)):
         if isinstance(o, set):
             seq_type = "Set"
         elif isinstance(o, list):
             seq_type = "List"
         elif isinstance(o, QuerySet):
             seq_type = "Queryset"
         else:
             seq_type = "Sequence (%s)" % (o,)
         try:
             o_l = len(o)
         except TypeError:
             o_l = "<Unknown>"
         if o_l == 0:
             self.render_row(results, label, force_escape("Empty %s" % seq_type))
             return
         o = iter(o).next()
         self.render_row(results, label, force_escape("%s of %s " % (seq_type, o_l)) + (
                         self.render_explanation(o)))
     else:
         self.render_row(results, label, self.render_explanation(o))
コード例 #3
0
    def render_explanation(self, o):
        if isinstance(o, HttpRequest):
            return "<a href='http://docs.djangoproject.com/en/dev/ref/request-response/#ref-request-response'>request object</a>"
        elif isinstance(o, (QuerySet,Model)):
            if isinstance(o, QuerySet):
                prefix = "Queryset of "
                o = o.model
            else:
                m = o
            #link to model docs
            app_label, model_name = o._meta.app_label, o._meta.object_name.lower()
            url = urlresolvers.reverse('django-admindocs-models-detail', args=[app_label, model_name])
            return "<a href='%s'>%s</a>" % (force_escape(url), 
                                            force_escape("%s.%s" % (app_label, model_name)))
        elif isinstance(o, Form):
            return "<p>%s fields:</p>\n<ul>%s</ul>" % (
            o.__class__.__name__,
            "\n".join(["<li>%s</li>" % force_escape(field) for field in o.fields])
            )
        elif isinstance(o, (set, list, tuple, dict)):
            return "group of %s items" % len(o)
        elif isinstance(o, (basestring, int, Decimal, float, datetime.date, datetime.time, datetime.datetime)):
            return force_escape(unicode(o))
        else:
            type_ = type(o)

            str_ = unicode(o)
            return force_escape("%s: %s" % (type_, str_))
コード例 #4
0
 def test_force_escape(self):
     escaped = force_escape('<some html & special characters > here')
     self.assertEqual(
         escaped, '&lt;some html &amp; special characters &gt; here')
     self.assertIsInstance(escaped, SafeData)
     self.assertEqual(
         force_escape('<some html & special characters > here ĐÅ€£'),
         '&lt;some html &amp; special characters &gt; here'
         ' \u0110\xc5\u20ac\xa3')
コード例 #5
0
ファイル: tests.py プロジェクト: AgentK1729/django
 def test_force_escape(self):
     escaped = force_escape('<some html & special characters > here')
     self.assertEqual(
         escaped, '&lt;some html &amp; special characters &gt; here')
     self.assertIsInstance(escaped, SafeData)
     self.assertEqual(
         force_escape('<some html & special characters > here ĐÅ€£'),
         '&lt;some html &amp; special characters &gt; here'
         ' \u0110\xc5\u20ac\xa3')
コード例 #6
0
def plugin_to_tag(obj):
    return (
        u'<img src="%(icon_src)s" alt="%(icon_alt)s" title="%(icon_alt)s" '
        u'id="plugin_obj_%(id)d" />' % (
            dict(
                id=obj.id, icon_src=force_escape(obj.get_instance_icon_src()),
                icon_alt=force_escape(obj.get_instance_icon_alt()),
            )
        )
    )
コード例 #7
0
ファイル: models.py プロジェクト: fiam/blangoblog
    def author_link(self):
        if self.user is not None:
            return mark_safe('<a href="%s">%s</a>' % \
                    (settings.BLANGO_URL, self.author_name))

        if self.author_uri:
            return mark_safe('<a rel="external nofollow" href="%s">%s</a>' % \
                    (self.author_uri, force_escape(self.author_name)))

        return mark_safe(force_escape(self.author))
コード例 #8
0
ファイル: util.py プロジェクト: conformist-mw/django-siteinfo
 def __unicode__(self, request=None):
     attrs = u''
     if self.name:
         attrs += u'name="%s" ' % force_escape(self.name)
     attrs += u'content="%s" ' % force_escape(self.content)
     if self.http_equiv:
         attrs += u'http-equiv="%s" ' % force_escape(self.http_equiv)
     if self.scheme:
         attrs += u'scheme="%s" ' % force_escape(self.scheme)
     return mark_safe(u'<meta %s/>' % attrs)
コード例 #9
0
ファイル: misc.py プロジェクト: haugvald/baruwa
def jsonify_msg_list(element):
    """
    Fixes the converting error in converting
    DATETIME objects to JSON
    """
    element["timestamp"] = str(element["timestamp"])
    element["sascore"] = str(element["sascore"])
    element["subject"] = force_escape(element["subject"])
    element["to_address"] = force_escape(element["to_address"])
    element["from_address"] = force_escape(element["from_address"])
    return element
コード例 #10
0
ファイル: forms.py プロジェクト: antineutron/baruwa
 def clean_to_address(self):
     to_address = self.cleaned_data['to_address']
     if not email_re.match(to_address):
         raise forms.ValidationError(
             '%s provide a valid e-mail address' % force_escape(to_address))
     if to_address not in self.request.session['user_filter']['addresses'] \
         and not self.request.user.is_superuser():
         raise forms.ValidationError(
             "The address: %s does not belong to you." % force_escape(
             to_address))
     return to_address
コード例 #11
0
ファイル: misc.py プロジェクト: baruwaproject/baruwa
def jsonify_msg_list(element):
    """
    Fixes the converting error in converting
    DATETIME objects to JSON
    """
    element['timestamp'] = str(element['timestamp'])
    element['sascore'] = str(element['sascore'])
    element['subject'] = force_escape(element['subject'])
    element['to_address'] = force_escape(element['to_address'])
    element['from_address'] = force_escape(element['from_address'])
    return element
コード例 #12
0
ファイル: misc.py プロジェクト: sandroden/baruwa
def jsonify_msg_list(element):
    """
    Fixes the converting error in converting
    DATETIME objects to JSON
    """
    element['timestamp'] = str(element['timestamp'])
    element['sascore'] = str(element['sascore'])
    element['subject'] = force_escape(element['subject'])
    element['to_address'] = force_escape(element['to_address'])
    element['from_address'] = force_escape(element['from_address'])
    return element
コード例 #13
0
ファイル: forms.py プロジェクト: ajendoubi/baruwa
 def clean_to_address(self):
     to_address = self.cleaned_data['to_address']
     if not email_re.match(to_address):
         raise forms.ValidationError(
             _('%(email)s provide a valid e-mail address') %
             {'email': force_escape(to_address)})
     if to_address not in self.request.session['user_filter']['addresses'] \
         and not self.request.user.is_superuser():
         raise forms.ValidationError(
             _("The address: %(email)s does not belong to you.") %
             {'email': force_escape(to_address)})
     return to_address
コード例 #14
0
    def edit_plugin(self, request, plugin_id):
        plugin_id = int(plugin_id)
        # get the plugin to edit of bail out
        cms_plugin = get_object_or_404(CMSPlugin, pk=plugin_id)

        if not has_plugin_permission(request.user, cms_plugin.plugin_type, "change"):
            return HttpResponseForbidden(_("You don't have permission to add plugins"))

        # check that the user has permission to change this plugin
        if not cms_plugin.placeholder.has_change_permission(request):
            return HttpResponseForbidden(_("You don't have permission to add content here."))
        
        instance, plugin_admin = cms_plugin.get_plugin_instance(self.admin_site)
        
        plugin_admin.cms_plugin_instance = cms_plugin
        plugin_admin.placeholder = cms_plugin.placeholder
        
        if request.method == "POST":
            # set the continue flag, otherwise will plugin_admin make redirect to list
            # view, which actually does'nt exists
            post_request = request.POST.copy()
            post_request['_continue'] = True
            request.POST = post_request
        
        if not instance:
            # instance doesn't exist, call add view
            response = plugin_admin.add_view(request)
     
        else:
            # already saved before, call change view
            # we actually have the instance here, but since i won't override
            # change_view method, is better if it will be loaded again, so
            # just pass id to plugin_admin
            response = plugin_admin.change_view(request, str(plugin_id))
        
        if request.method == "POST" and plugin_admin.object_successfully_changed:
            # read the saved object from plugin_admin - ugly but works
            saved_object = plugin_admin.saved_object
            
            context = {
                'CMS_MEDIA_URL': settings.CMS_MEDIA_URL, 
                'plugin': saved_object, 
                'is_popup': True, 
                'name': unicode(saved_object), 
                "type": saved_object.get_plugin_name(),
                'plugin_id': plugin_id,
                'icon': force_escape(escapejs(saved_object.get_instance_icon_src())),
                'alt': force_escape(escapejs(saved_object.get_instance_icon_alt())),
            }
            return render_to_response('admin/cms/page/plugin_forms_ok.html', context, RequestContext(request))
            
        return response
コード例 #15
0
 def _tag_to_admin(m):
     plugin_id = int(m.groups()[0])
     try:
         obj = CMSPlugin.objects.get(pk=plugin_id)
     except CMSPlugin.DoesNotExist:
         # Object must have been deleted.  It cannot be rendered to
         # end user, or edited, so just remove it from the HTML
         # altogether
         return u''
     return u'<img src="%(icon_src)s" alt="%(icon_alt)s" title="%(icon_alt)s" id="plugin_obj_%(id)d" />' % \
            dict(id=plugin_id,
                 icon_src=force_escape(obj.get_instance_icon_src()),
                 icon_alt=force_escape(obj.get_instance_icon_alt()),
                 )
コード例 #16
0
ファイル: plugin_base.py プロジェクト: SpivEgin/devenv
    def render_close_frame(self, obj, extra_context=None):
        context = {
            'plugin': obj,
            'is_popup': True,
            'name': force_text(obj),
            "type": obj.get_plugin_name(),
            'plugin_id': obj.pk,
            'icon': force_escape(obj.get_instance_icon_src()),
            'alt': force_escape(obj.get_instance_icon_alt()),
        }

        if extra_context:
            context.update(extra_context)
        return render_to_response('admin/cms/page/plugin/confirm_form.html',
                                  context)
コード例 #17
0
ファイル: views.py プロジェクト: cc1-cloud/cc1
def generic_multiple_id(request, template_name=None, success_msg=lambda x: _('Success'),
                        ask_msg=lambda x, y: _('Do you want to?'), confirmation=_('Yes'), request_url=None, id_key=None):
    """
    Generic ajax view for handling dialogs working on multiple items.
    """
    if request.method == 'POST':
        id_list = request.POST.getlist('ids[]')

        if id_key is None:
                raise Exception('\'id_key\' not set in urls')

        if request_url is None:
            raise Exception("No 'request_url' specified.")

        response = prep_data((request_url, {id_key: [int(a) for a in id_list]}), request.session)
        if response is None:
            return messages_ajax.success(success_msg(request.POST.get('desc'), int(request.POST.get('length'))))
        return _multiple_id_return(response, id_list, request.POST.get('desc'), success_msg)
    else:
        if request.GET.get('length') is None:
            return messages_ajax.error(_("Bad argument list"))
        return messages_ajax.success(render_to_string(template_name,
                                                   {'text': ask_msg(force_escape(request.GET.get('desc')), int(request.GET.get('length'))),
                                                    'confirmation': confirmation},
                                                   context_instance=RequestContext(request)))
コード例 #18
0
ファイル: views.py プロジェクト: cc1-cloud/cc1
def simple_generic_twoid(request, id1, id2, template_name=None, success_msg=lambda desc: _('Success') % {'desc': desc}, ask_msg=lambda x: '',
                         confirmation=_('Yes'), request_url=None, param=None, id_key=None, id_key2=None):
    """
    Simple generic ajax view for creating dialogs (2 entities).
    """
    if request.method == 'POST':
        if request_url is None:
            raise Exception("No 'request_url' specified.")

        args = {}
        if id1 is not None:
            if id_key is None:
                raise Exception('\'id_key\' not set in urls')
            args[id_key] = int(id1)

        if id2 is not None:
            if id_key2 is None:
                raise Exception('\'id_key2\' not set in urls')
            args[id_key2] = int(id2)

        if param is not None:
            args.update(param)

        prep_data((request_url, args), request.session)
        return messages_ajax.success(success_msg(force_escape(request.REQUEST.get('desc'))))

    if template_name is not None:
        return messages_ajax.success(render_to_string(template_name, {'text': ask_msg(force_escape(request.REQUEST.get('desc'))),
                                                                      'confirmation': confirmation, 'id': id1}, context_instance=RequestContext(request)))
コード例 #19
0
def cma_ajax_copy_iso(request,
                      id1,
                      template_name='generic/form.html',
                      form_class=CopyToUserForm):
    """
    Ajax view for changing the image owner.
    """
    rest_data = prep_data({'users': 'admin_cm/user/get_list/'},
                          request.session)

    if request.method == 'POST':
        form = form_class(data=request.POST,
                          files=request.FILES,
                          rest_data=rest_data)
        if form.is_valid():
            dictionary = form.cleaned_data
            dictionary['src_image_id'] = int(id1)
            dictionary['dest_user_id'] = int(dictionary['dest_user_id'])

            prep_data(('admin_cm/iso_image/copy/', dictionary),
                      request.session)

            return messages_ajax.success(
                _("<b>%(desc)s</b> copied.") %
                {'desc': force_escape(request.REQUEST.get('desc'))})
    else:
        form = form_class(rest_data=rest_data)
    return messages_ajax.success(render_to_string(
        template_name, {
            'form': form,
            'confirmation': _('Copy'),
            'text': _('Select user:')
        },
        context_instance=RequestContext(request)),
                                 status=1)
コード例 #20
0
ファイル: filter.py プロジェクト: jonaqp/django_inei
def advanced_label_tag(field):
    """ Return form field label html marked to fill by `*` """
    classes = []
    attrs = {}
    from django.utils.encoding import force_text
    from django.template.defaultfilters import force_escape

    contents = force_text(force_escape(field.label))
    if field.field.required:
        classes.append(u'text-semibold')
        contents = force_text(u'{0:s}'.format(force_escape(field.label)))

    if classes:
        attrs['class'] = u' '.join(classes)

    return field.label_tag(contents=contents, attrs=attrs)
コード例 #21
0
ファイル: forms.py プロジェクト: haugvald/baruwa
    def clean(self):
        """
        Validates the quarantine form
        """
        cleaned_data = self.cleaned_data
        use_alt = cleaned_data.get("use_alt")
        altrecipients = cleaned_data.get("altrecipients")
        learn = cleaned_data.get("learn")
        release = cleaned_data.get("release")
        todelete = cleaned_data.get("todelete")

        if not learn and not release and not todelete:
            raise forms.ValidationError(
                _("Select atleast one action to perform"))
        else:
            if altrecipients in EMPTY_VALUES and use_alt and release:
                raise forms.ValidationError(
                    _("Provide atleast one alternative recipient"))
            else:
                if use_alt and release:
                    emails = altrecipients.split(',')
                    for email in emails:
                        if not email_re.match(email.strip()):
                            raise forms.ValidationError(
                                _('%(email)s is not a valid e-mail address.') %
                                {'email': force_escape(email)})
        return cleaned_data
コード例 #22
0
ファイル: views.py プロジェクト: itsbenweeks/Amara
def onsite_widget(request):
    """Used for subtitle dialog"""

    context = widget.add_config_based_js_files({}, settings.JS_API,
                                               'unisubs-api.js')
    config = request.GET.get('config', '{}')
    # strip any query string parama as that chokes the json string
    match = re.search(r'(?P<qs>}\?.*)', config)
    if match:
        config = config[:match.start() + 1]
    try:
        config = json.loads(config)
    except (ValueError, KeyError):
        raise Http404

    if config.get('task'):
        task = get_object_or_404(Task, pk=config.get('task'))
        if task.completed:
            messages.error(request,
                           _(u'That task has already been completed.'))
            return HttpResponseRedirect(
                reverse('teams:team_tasks', kwargs={'slug': task.team.slug}))

    if not config.get('nullWidget'):
        video_id = config.get('videoID')

        if not video_id:
            raise Http404

        video = get_object_or_404(models.Video, video_id=video_id)
        config['returnURL'] = video.get_absolute_url()

        if not 'effectiveVideoURL' in config:
            config['effectiveVideoURL'] = video.get_video_url()

        tv = video.get_team_video()
        if tv:
            team = tv.team

            config['guidelines'] = dict([
                (s.key_name.split('_', 1)[-1],
                 linebreaks(urlize(force_escape(s.data))))
                for s in team.settings.guidelines() if s.data.strip()
            ])

            # TODO: Go to the tasks panel once the history stuff is implemented
            config['team_url'] = reverse('teams:settings_basic',
                                         kwargs={'slug': team.slug})
        else:
            config['guidelines'] = {}

    context['widget_params'] = json.dumps(config)
    general_settings = {}
    add_general_settings(request, general_settings)
    context['general_settings'] = json.dumps(general_settings)
    response = render_to_response('widget/onsite_widget.html',
                                  context,
                                  context_instance=RequestContext(request))
    response['X-XSS-Protection'] = '0'
    return response
コード例 #23
0
ファイル: alliance.py プロジェクト: anih/ugame_alt
    def site_chat_get(self):
        user = self.user
        last_id = self.request.REQUEST.get("id", 0)
        try:
            sojusz = user.czlonkowie.sojusz
        except Sojusz.DoesNotExist:
            return {
                "rows": [{
                    "user": "******",
                    "wiadomosc": "Nie jesteś w sojuszu"
                }]
            }

        if not last_id > 0:
            count = SojuszChat.objects.filter(sojusz=sojusz,
                                              id__gt=last_id).count() - 20
            if count < 0:
                count = 0
            wiadomosci = SojuszChat.objects.filter(sojusz=sojusz)[count:]
        else:
            wiadomosci = SojuszChat.objects.filter(sojusz=sojusz,
                                                   id__gt=last_id)
        rows = []
        for w in wiadomosci:
            rows.append({
                "id": w.pk,
                "user": w.user.username,
                "wiadomosc": force_escape(striptags(w.wiadomosc))
            })

        return {"rows": rows}
コード例 #24
0
def linkify(obj, link_text=''):
    """turns object(s) into (html) link(s).

    if objects have the attr 'domain', stick the domain in the URL.
    """
    try:
        lst = []
        # if obj is not a list, convert it into a list
        if not getattr(obj, '__iter__', False):
            obj = [obj]
        for item in obj:
            if hasattr(item, 'child'):
                item = item.child
            if link_text == '':
                l_text = unicode(item)
            else:
                try:
                    link_text = link_text.encode('ascii')
                    l_text = getattr(item, link_text, link_text)
                except UnicodeEncodeError:
                    l_text = link_text
            if not (isinstance(item, Content)
                    and isinstance(l_text, SafeText)):
                l_text = filter.force_escape(l_text)
            format_args = (item.get_absolute_url(), l_text)
            lst.append(mark_safe('<a href=\'%s\'>%s</a>' % format_args))

        # nonlists obj's should be returned as nonlists
        return lst[0] if len(lst) == 1 else lst
    except:
        return ''
コード例 #25
0
def plugin_options(channel, channel_name, widget_plugin_options, initial):
    """ Make a JSON dumped dict of all options for the jquery ui plugin itself """
    po = {}
    if initial:
        po['initial'] = initial
    po.update(getattr(channel, 'plugin_options', {}))
    po.update(widget_plugin_options)
    if not po.get('min_length'):
        # backward compatibility: honor the channel's min_length attribute
        # will deprecate that some day and prefer to use plugin_options
        po['min_length'] = getattr(channel, 'min_length', 1)
    if not po.get('source'):
        po['source'] = reverse('ajax_lookup', kwargs={'channel': channel_name})

    # allow html unless explictly false
    if po.get('html') is None:
        po['html'] = True

    return {
        'plugin_options': mark_safe(json.dumps(po)),
        'data_plugin_options': force_escape(json.dumps(po)),
        # continue to support any custom templates that still expect these
        'lookup_url': po['source'],
        'min_length': po['min_length']
        }
コード例 #26
0
ファイル: plugin_base.py プロジェクト: evildmp/django-cms
    def render_close_frame(self, obj, extra_context=None):
        context = {
            'plugin': obj,
            'is_popup': True,
            'name': force_text(obj),
            "type": obj.get_plugin_name(),
            'plugin_id': obj.pk,
            'icon': force_escape(obj.get_instance_icon_src()),
            'alt': force_escape(obj.get_instance_icon_alt()),
        }

        if extra_context:
            context.update(extra_context)
        return render_to_response(
            'admin/cms/page/plugin/confirm_form.html', context
        )
コード例 #27
0
ファイル: forms.py プロジェクト: antineutron/baruwa
    def clean(self):
        """
        Validates the quarantine form
        """
        cleaned_data = self.cleaned_data
        use_alt = cleaned_data.get("use_alt")
        altrecipients = cleaned_data.get("altrecipients")
        salearn = cleaned_data.get("salearn")
        release = cleaned_data.get("release")
        todelete = cleaned_data.get("todelete")

        if not salearn and not release and not todelete:
            raise forms.ValidationError("Select atleast one action to perform")
        else:
            if altrecipients in EMPTY_VALUES and use_alt and release:
                raise forms.ValidationError(
                    "Provide atleast one alternative recipient")
            else:
                if use_alt and release:
                    emails = altrecipients.split(',')
                    for email in emails:
                        if not email_re.match(email.strip()):
                            raise forms.ValidationError(
                            '%s is not a valid e-mail address.' 
                            % force_escape(email))
        return cleaned_data
コード例 #28
0
ファイル: common.py プロジェクト: bjacobel/crimsononline
def linkify(obj, link_text=''):
    """turns object(s) into (html) link(s).

    if objects have the attr 'domain', stick the domain in the URL.
    """
    try:
        l = []
        # if obj is not a list, convert it into a list
        if not getattr(obj,'__iter__',False):
            obj = [obj]
        for item in obj:
            if link_text == '':
                l_text = item
            else: # if link_text is not ascii, can't call getattr on it
                try:
                    link_text = link_text.encode('ascii')
                    l_text = getattr(item, link_text, link_text)
                except UnicodeEncodeError:
                    l_text = link_text
            l.append(mark_safe('<a href="%s">%s</a>' % \
                (item.get_absolute_url(), filter.force_escape(l_text))))
        # nonlists obj's should be returned as nonlists
        return l[0] if len(l) == 1 else l
    except:
        return ''
コード例 #29
0
ファイル: views.py プロジェクト: mccutchen/watercooler
def post(request, slug):
    """Adds a post to the chat identified by the given slug.  Also
    updates the current user's latest ping time, reflecting activity
    in this chat.

    This view will handle either normal POSTs or POSTs via Ajax (in
    which case it returns a JSON response with the timestamp of the
    created post and the post's HTML-escaped content."""
    chat = get_object_or_404(Chat, slug=slug)
    if request.POST:
        content = request.POST.get('content', '')
        post = Post(user=request.user, parent=chat, content=content)
        post.save()

        # Update the user's last ping value to reflect active
        # participation in this chat.
        user_ping(request.user)

        # If we're processing an Ajax request, return the timestamp of
        # the post we just created and its HTML-escaped content in
        # JSON format.
        if request.is_ajax():
            response = json.dumps({
                'timestamp': post.timestamp(),
                'content': force_escape(post.content),
            })
            return HttpResponse(response, mimetype='application/json')

    # Redirect the user back to this chat's page for normal, non-Ajax
    # requests.
    return HttpResponseRedirect(chat.get_absolute_url())
コード例 #30
0
    def do_render(self, header="", lang='html', status=None, wide=False):
        output = []

        code = self.nodelist.render({})
        code = dedent(code).strip()


        if header or status:
            output.append('<h4 class="%s">%s</h4>' % (
                (' styleguide-status-'+status if status else ''),
                header,
            ))
        classes = ['styleguide-example']
        if wide:
            classes.append('styleguide-example-wide')
        classes = ' '.join(classes)
        output.append('<div class="%s">' % classes)
        output.append('<div class=styleguide-code>')

        output.append('<pre><code class=%s>' %  lang)
        output.append(defaultfilters.force_escape(code))
        output.append('</code></pre>')

        output.append('</div>')
        output.append('<div class=styleguide-sep><span>➵</span></div>')
        output.append('<div class=styleguide-demo>')

        output.append(code)

        output.append('</div></div>')

        return ''.join(output)
コード例 #31
0
def plugin_options(channel, channel_name, widget_plugin_options, initial):
    """ Make a JSON dumped dict of all options for the jquery ui plugin itself """
    po = {}
    if initial:
        po['initial'] = initial
    po.update(getattr(channel, 'plugin_options', {}))
    po.update(widget_plugin_options)
    if not po.get('min_length'):
        # backward compatibility: honor the channel's min_length attribute
        # will deprecate that some day and prefer to use plugin_options
        po['min_length'] = getattr(channel, 'min_length', 1)
    if not po.get('source'):
        po['source'] = reverse('ajax_lookup', kwargs={'channel': channel_name})

    # allow html unless explictly false
    if po.get('html') is None:
        po['html'] = True

    return {
        'plugin_options': mark_safe(json.dumps(po)),
        'data_plugin_options': force_escape(json.dumps(po)),
        # continue to support any custom templates that still expect these
        'lookup_url': po['source'],
        'min_length': po['min_length']
    }
コード例 #32
0
ファイル: views.py プロジェクト: cc1-cloud/cc1
def form_generic_id(request, id1, template_name=None, form_class=None,
                    request_url_post=None, request_url_get=None,
                    success_msg=lambda desc: _('Success'), ask_msg=lambda x: '', confirmation=_('Yes'),
                    request_url_both=None, ajax_success_status=0, id_key=None):
    """
    Generic ajax view for dialog handling.
    """
    rest_data1 = prep_data(request_url_both, request.session)

    if request.method == 'POST':
        kwargs = {}
        if rest_data1 is not None:
            kwargs['rest_data'] = rest_data1
        form = form_class(request.POST, **kwargs)

        if form.is_valid():
            args = {}

            if id1 is not None:
                if id_key is None:
                    raise Exception('\'id_key\' not set in urls')
                args[id_key] = int(id1)
            args.update(form.cleaned_data)

            rest_data2 = prep_data((request_url_post, args), request.session)
            return messages_ajax.success(success_msg(force_escape(request.REQUEST.get('desc')), rest_data2),
                                         status=ajax_success_status)
    else:
        args = []
        kwargs = {}

        if request_url_get is not None and id1 is not None:
            response = prep_data((request_url_get, {id_key: id1}), request.session)

            args.append(response)

        if rest_data1 is not None:
            kwargs['rest_data'] = rest_data1

        form = form_class(*args, **kwargs)

    return messages_ajax.success(render_to_string(template_name, {'form': form,
                                                                  'text': ask_msg(force_escape(request.REQUEST.get('desc'))),
                                                                  'confirmation': confirmation,
                                                                  'id': id1},
                                                   context_instance=RequestContext(request)),
                                  status=1)
コード例 #33
0
ファイル: frontend_extras.py プロジェクト: thawatchai/portals
def append_page(portal, l, page, req_page, ul=''):
    l.append('<li page_id="%s" %s><a href="%s"><span %s>%s</span></a>%s</li>' % (
        page.id,
        'class="expanded"' if ul or page == req_page else '',
        domain_reverse(portal, 'portals.frontend.views.page_item', args=[portal.address, page.slug if page.slug else page.id]),
        'class="selected"' if page == req_page else '',
        force_escape(page.title),
        ul))
コード例 #34
0
ファイル: views.py プロジェクト: th3n3xtg3n3ration/cc1
def simple_generic_twoid(
        request,
        id1,
        id2,
        template_name=None,
        success_msg=lambda desc: _('Success') % {'desc': desc},
        ask_msg=lambda x: '',
        confirmation=_('Yes'),
        request_url=None,
        param=None,
        id_key=None,
        id_key2=None):
    """
    Simple generic ajax view for creating dialogs (2 entities).
    """
    if request.method == 'POST':
        if request_url is None:
            raise Exception("No 'request_url' specified.")

        args = {}
        if id1 is not None:
            if id_key is None:
                raise Exception('\'id_key\' not set in urls')
            args[id_key] = int(id1)

        if id2 is not None:
            if id_key2 is None:
                raise Exception('\'id_key2\' not set in urls')
            args[id_key2] = int(id2)

        if param is not None:
            args.update(param)

        prep_data((request_url, args), request.session)
        return messages_ajax.success(
            success_msg(force_escape(request.REQUEST.get('desc'))))

    if template_name is not None:
        return messages_ajax.success(
            render_to_string(
                template_name, {
                    'text': ask_msg(force_escape(request.REQUEST.get('desc'))),
                    'confirmation': confirmation,
                    'id': id1
                },
                context_instance=RequestContext(request)))
コード例 #35
0
    def to_db(cls, value, **kwargs):
        if not isinstance(value, string_types):
            raise cls.exception("Cannot serialize, value {0} is not a string".format(value))

        if kwargs.get("escape_html", False):
            return defaultfilters.force_escape(value)
        else:
            return value
コード例 #36
0
 def serialize(cls, value, **kwargs):
     if not isinstance(value, string_types):
         raise cls.exception(
             "Cannot serialize, value {0} is not a string".format(value))
     if kwargs.get("escape_html", False):
         return defaultfilters.force_escape(value.encode('utf-8'))
     else:
         return value.encode('utf-8')
コード例 #37
0
ファイル: html_to_pdf.py プロジェクト: AnderLinares/django_e
 def render_to_pdf(template_src, context_dict):
     template = get_template(template_src)
     context = Context(context_dict)
     html = template.render(context)
     result = StringIO()
     pdf = pisaDocument(StringIO(html.encode("ISO-8859-1")), result)
     if not pdf.err:
         return HttpResponse(result.getvalue(), content_type='application/pdf')
     return HttpResponse('We had some errors<pre>%s</pre>' % force_escape(html))
コード例 #38
0
ファイル: util.py プロジェクト: lek6/django-cms
 def __unicode__(self, request=None):
     if not self.lang:
         if not request:
             lang = settings.LANGUAGE_CODE[:2]
         else:
             lang = request.LANGUAGE_CODE[:2]
     else:
         lang = self.lang
     attrs = u''
     if self.name:
         attrs += u'name="%s" ' % force_escape(self.name)
     attrs += u'content="%s" ' % force_escape(self.content)
     if self.http_equiv:
         attrs += u'http_equiv="%s" ' % force_escape(self.http_equiv)
     if self.scheme:
         attrs += u'scheme="%s" ' % force_escape(self.scheme)
     attrs += u'lang="%s" ' % force_escape(lang)
     return mark_safe(u'<meta %s/>' % attrs)
コード例 #39
0
    def get_traceback_data(self):
        """Return a dictionary containing traceback information."""
        if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
            self.template_does_not_exist = True
            self.postmortem = self.exc_value.chain or [self.exc_value]

        frames = self.get_traceback_frames()
        for i, frame in enumerate(frames):
            if 'vars' in frame:
                frame_vars = []
                for k, v in frame['vars']:
                    v = pprint(v)
                    # The force_escape filter assume unicode, make sure that works
                    if isinstance(v, six.binary_type):
                        v = v.decode('utf-8', 'replace')  # don't choke on non-utf-8 input
                    # Trim large blobs of data
                    if len(v) > 4096:
                        v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v))
                    frame_vars.append((k, force_escape(v)))
                frame['vars'] = frame_vars
            frames[i] = frame

        unicode_hint = ''
        if self.exc_type and issubclass(self.exc_type, UnicodeError):
            start = getattr(self.exc_value, 'start', None)
            end = getattr(self.exc_value, 'end', None)
            if start is not None and end is not None:
                unicode_str = self.exc_value.args[1]
                unicode_hint = smart_text(
                    unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))],
                    'ascii', errors='replace'
                )
        from django import get_version
        c = {
            'is_email': self.is_email,
            'unicode_hint': unicode_hint,
            'frames': frames,
            'request': self.request,
            'filtered_POST': self.filter.get_post_parameters(self.request),
            'settings': get_safe_settings(),
            'sys_executable': sys.executable,
            'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
            'server_time': timezone.now(),
            'django_version_info': get_version(),
            'sys_path': sys.path,
            'template_info': self.template_info,
            'template_does_not_exist': self.template_does_not_exist,
            'postmortem': self.postmortem,
        }
        # Check whether exception info is available
        if self.exc_type:
            c['exception_type'] = self.exc_type.__name__
        if self.exc_value:
            c['exception_value'] = smart_text(self.exc_value, errors='replace')
        if frames:
            c['lastframe'] = frames[-1]
        return c
コード例 #40
0
ファイル: admin.py プロジェクト: miing/mci_migo
    def account_link(self, obj):
        if obj.account is None:
            return "None"

        url = reverse(
            'admin:identityprovider_account_change', args=(obj.account.id,))
        snippet = '<a href="%s">%s</a>'
        info = (url, force_escape(obj.account.displayname))
        return snippet % info
コード例 #41
0
ファイル: util.py プロジェクト: lek6/django-cms
 def __unicode__(self, request=None):
     if not self.lang:
         if not request:
             lang = settings.LANGUAGE_CODE[:2]
         else:
             lang = request.LANGUAGE_CODE[:2]
     else:
         lang = self.lang
     attrs = u''
     if self.name:
         attrs += u'name="%s" ' % force_escape(self.name)
     attrs += u'content="%s" ' % force_escape(self.content)
     if self.http_equiv:
         attrs += u'http_equiv="%s" ' % force_escape(self.http_equiv)
     if self.scheme:
         attrs += u'scheme="%s" ' % force_escape(self.scheme)
     attrs += u'lang="%s" ' % force_escape(lang)
     return mark_safe(u'<meta %s/>' % attrs)
コード例 #42
0
def simple_formatting(value):
    value = force_escape(value)
    value = value.replace("\r\n", "\n")
    value = "<p>%s</p>" % value
    value = re.sub("(?sum)\n\n", "\n\n</p><p>", value)
    value = re.sub("(?sum)</p><p>(\s+)</p><p>", "\\1</p><p>", value)
    value = re.sub("(?sum)[ ]+"," ", value)
    value = value.replace("\n", "<br>\n")
    return mark_safe(value)
コード例 #43
0
ファイル: debug.py プロジェクト: HenryJohnOh/django
    def get_traceback_data(self):
        """Return a dictionary containing traceback information."""
        if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
            self.template_does_not_exist = True
            self.postmortem = self.exc_value.chain or [self.exc_value]

        frames = self.get_traceback_frames()
        for i, frame in enumerate(frames):
            if 'vars' in frame:
                frame_vars = []
                for k, v in frame['vars']:
                    v = pprint(v)
                    # The force_escape filter assume unicode, make sure that works
                    if isinstance(v, six.binary_type):
                        v = v.decode('utf-8', 'replace')  # don't choke on non-utf-8 input
                    # Trim large blobs of data
                    if len(v) > 4096:
                        v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v))
                    frame_vars.append((k, force_escape(v)))
                frame['vars'] = frame_vars
            frames[i] = frame

        unicode_hint = ''
        if self.exc_type and issubclass(self.exc_type, UnicodeError):
            start = getattr(self.exc_value, 'start', None)
            end = getattr(self.exc_value, 'end', None)
            if start is not None and end is not None:
                unicode_str = self.exc_value.args[1]
                unicode_hint = smart_text(
                    unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))],
                    'ascii', errors='replace'
                )
        from django import get_version
        c = {
            'is_email': self.is_email,
            'unicode_hint': unicode_hint,
            'frames': frames,
            'request': self.request,
            'filtered_POST': self.filter.get_post_parameters(self.request),
            'settings': get_safe_settings(),
            'sys_executable': sys.executable,
            'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
            'server_time': timezone.now(),
            'django_version_info': get_version(),
            'sys_path': sys.path,
            'template_info': self.template_info,
            'template_does_not_exist': self.template_does_not_exist,
            'postmortem': self.postmortem,
        }
        # Check whether exception info is available
        if self.exc_type:
            c['exception_type'] = self.exc_type.__name__
        if self.exc_value:
            c['exception_value'] = smart_text(self.exc_value, errors='replace')
        if frames:
            c['lastframe'] = frames[-1]
        return c
コード例 #44
0
def _context_helper(path, o, depth, seen, result):
    if depth > MAX_DEPTH:
        result.append("<tr><td>Too much nesting in context</td><td>Giving up.</td><td>&nbsp;</td></tr>")
        return
    h = _hash(o)
    if h in seen:
        result.append("<tr><td>%s</td><td>Previously reached.</td><td>Skipped</td></tr>" % (force_escape(".".join(path)),))
        return
    seen.add(h)
    result.append("<tr><td>%s</td><td>%s</td><td>" % (force_escape(".".join(path)), force_escape(_type_helper(o)[:100])))
    if isinstance(o, (list, dict, set, tuple)):
        result.append("<table>")
        if isinstance(o, dict):
            iter_ = lambda o:o.items()[:100]
        elif isinstance(o, tuple):
            iter_ = lambda o:list(enumerate(o))
        else:
            iter_ = lambda o:list(enumerate(o))[:5]
        for k,v in iter_(o):
            _context_helper(path + [k], v, depth+1, seen, result)
        result.append("</table>")
    elif isinstance(o, (QuerySet, Model)):
        if isinstance(o, Model):
            meta = o._meta
        else:
            meta = o.model._meta
        app_label, model_name = meta.app_label, meta.object_name.lower()
        url = urlresolvers.reverse('django-admindocs-models-detail', args=[app_label, model_name])
        label = "%s.%s" % (app_label, model_name)
        result.append("<a href='%s'>doc for %s</a>" % (url, label))
    elif isinstance(o, Form):
        result.append("<table><tr><th>name</th><th>type</th><th>value</th></tr>")
        for bound_field in o:
            _context_helper(path + [bound_field.name], bound_field, depth+1, seen, result)
        result.append("</table>")
    else:
        if hasattr(o, '__unicode__'):
            val = unicode(o)
        else:
            val = repr(o)
        if len(val) > 100:
            val = val[:97] + "..."
        result.append(force_escape(val))
    result.append("</td></tr>")
コード例 #45
0
 def get_team_editor_data(self):
     if self.team_video:
         team = self.team_video.team
         return dict([('teamName', team.name), ('type', team.workflow_type), ('guidelines', dict(
             [(s.key_name.split('_', 1)[-1],
               linebreaks(urlize(force_escape(s.data))))
              for s in team.settings.guidelines()
              if s.data.strip()]))])
     else:
         return None
コード例 #46
0
ファイル: plugin_base.py プロジェクト: diox/django-cms-2.0
 def response_add(self, request, obj, post_url_continue=None):
     """
     Overload the admin.ModelAdmin method.
     This method is called by the ModelAdmin.add_view.
     It make the Http response if forms is valid and object created.
     The template scope is to close the modal and reload the page.
     """
     context = {
         'CMS_MEDIA_URL': settings.CMS_MEDIA_URL, 
         'plugin': obj, 
         'is_popup': True, 
         'name': unicode(obj), 
         "type": obj.get_plugin_name(),
         'plugin_id': obj.pk,
         'icon': force_escape(escapejs(obj.get_instance_icon_src())),
         'alt': force_escape(escapejs(obj.get_instance_icon_alt())),
     }
     return render_to_response('admin/cms/page/plugin_forms_ok.html', 
                               context, RequestContext(request))
コード例 #47
0
 def insert_stack(self, request, placeholder_id):
     placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
     form = StackInsertionForm(
         initial={'language_code': request.GET.get('language_code', '')})
     if request.method == 'POST':
         form = StackInsertionForm(data=request.POST)
         if form.is_valid():
             context = {
                 'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'),
                 'is_popup': True,
                 'cancel': False,
             }
             if form.cleaned_data[
                     'insertion_type'] == StackInsertionForm.INSERT_LINK:
                 cms_plugin = add_plugin(placeholder,
                                         StackPlugin,
                                         form.cleaned_data['language_code'],
                                         stack=form.cleaned_data['stack'])
                 context.update({
                     'plugin':
                     cms_plugin,
                     "type":
                     cms_plugin.get_plugin_name(),
                     'plugin_id':
                     cms_plugin.pk,
                     'icon':
                     force_escape(
                         escapejs(cms_plugin.get_instance_icon_src())),
                     'alt':
                     force_escape(
                         escapejs(cms_plugin.get_instance_icon_alt())),
                 })
             else:
                 plugin_ziplist = copy_plugins_to(
                     list(form.cleaned_data['stack'].content.get_plugins()),
                     placeholder)
                 # TODO: once we actually use the plugin context in the frontend, we have to support multiple plugins
             return TemplateResponse(
                 request, 'admin/cms/page/plugin/confirm_form.html',
                 context)
     return TemplateResponse(request, 'admin/stacks/insert_stack.html', {
         'form': form,
     })
コード例 #48
0
def document_verify(request, document_pk):
    document = get_object_or_404(Document, pk=document_pk)

    try:
        Permission.check_permissions(
            request.user, (permission_document_verify,)
        )
    except PermissionDenied:
        AccessControlList.objects.check_access(
            permission_document_verify, request.user, document
        )

    document.add_as_recent_document_for_user(request.user)

    try:
        signature = DocumentVersionSignature.objects.verify_signature(
            document.latest_version
        )
    except AttributeError:
        signature_state = SIGNATURE_STATES.get(SIGNATURE_STATE_NONE)
        signature = None
    else:
        signature_state = SIGNATURE_STATES.get(
            getattr(signature, 'status', None)
        )

    paragraphs = [_('Signature status: %s') % signature_state['text']]

    try:
        if DocumentVersionSignature.objects.has_embedded_signature(document.latest_version):
            signature_type = _('Embedded')
        else:
            signature_type = _('Detached')
    except ValueError:
        signature_type = _('None')

    if signature:
        paragraphs.extend(
            [
                _('Signature ID: %s') % signature.signature_id,
                _('Signature type: %s') % signature_type,
                _('Key ID: %s') % signature.key_id,
                _('Timestamp: %s') % datetime.fromtimestamp(
                    int(signature.sig_timestamp)
                ),
                _('Signee: %s') % force_escape(getattr(signature, 'username', '')),
            ]
        )

    return render_to_response('appearance/generic_template.html', {
        'document': document,
        'object': document,
        'paragraphs': paragraphs,
        'title': _('Signature properties for document: %s') % document,
    }, context_instance=RequestContext(request))
コード例 #49
0
ファイル: views.py プロジェクト: th3n3xtg3n3ration/cc1
def generic_multiple_id_form(request,
                             template_name=None,
                             success_msg=lambda x: _('Success'),
                             ask_msg=lambda x, y: _('Do you want to?'),
                             confirmation=_('Yes'),
                             request_url=None,
                             form_class=None,
                             request_url_both=None,
                             id_key=None):
    """
    Generic ajax view for handling dialogs working on multiple items (with a form).
    """
    response1 = prep_data(request_url_both, request.session)

    if request.method == 'POST':
        if id_key is None:
            raise Exception('\'id_key\' not set in urls')

        if request_url is None:
            raise Exception("No 'request_url' specified.")

        kwargs = {}
        if response1 is not None:
            kwargs['rest_data'] = response1
        form = form_class(request.POST, **kwargs)

        if form.is_valid():
            id_list = [int(a) for a in request.POST.getlist('ids[]')]
            dictionary = {id_key: id_list}
            dictionary.update(form.cleaned_data)
            response2 = prep_data((request_url, dictionary), request.session)

            return _multiple_id_return(response2, id_list,
                                       request.POST.get('desc'), success_msg)
    else:
        args = []
        kwargs = {}

        if response1 is not None:
            kwargs['rest_data'] = response1

        form = form_class(*args, **kwargs)

    return messages_ajax.success(render_to_string(
        template_name, {
            'form':
            form,
            'text':
            ask_msg(force_escape(request.REQUEST.get('desc')),
                    int(request.REQUEST.get('length'))),
            'confirmation':
            confirmation
        },
        context_instance=RequestContext(request)),
                                 status=1)
コード例 #50
0
ファイル: pdf.py プロジェクト: firesalp/aemanager
    def add_rows(self, rows):
        row_count = 0
        extra_rows = 0
        extra_style = []
        data = []
        data.append([ugettext('Label'), ugettext('Quantity'), ugettext('Unit price'), ugettext('Total excl tax')])
        if self.user.get_profile().vat_number:
            data[0].append(ugettext('VAT'))
            label_width = 4.0 * inch
        else:
            label_width = 4.5 * inch
        for row in rows:
            row_count += 1
            label = self.get_label(row)
            #label = label.replace('&', '[et]')
            para = Paragraph(force_escape(label), ProposalTemplate.styleLabel)
            para.width = label_width
            splitted_para = para.breakLines(label_width)
            label = self.get_splitted_content(splitted_para.lines[0])
            quantity = row.quantity
            quantity = quantity.quantize(Decimal(1)) if quantity == quantity.to_integral() else quantity.normalize()
            unit_price = row.unit_price
            unit_price = unit_price.quantize(Decimal(1)) if unit_price == unit_price.to_integral() else unit_price.normalize()
            total = row.quantity * row.unit_price
            total = total.quantize(Decimal(1)) if total == total.to_integral() else total.normalize()
            data_row = [label, localize(quantity), "%s %s" % (localize(unit_price), "€".decode('utf-8')), "%s %s" % (localize(total), "€".decode('utf-8'))]
            if self.user.get_profile().vat_number:
                if row.vat_rate:
                    data_row.append("%s%%" % (localize(row.vat_rate)))
                else:
                    data_row.append('-')
            data.append(data_row)

            for extra_row in splitted_para.lines[1:]:
                label = self.get_splitted_content(extra_row)
                if self.user.get_profile().vat_number:
                    data.append([label, '', '', '', ''])
                else:
                    data.append([label, '', '', ''])
                extra_rows += 1

            extra_detail_rows = self.add_row_detail(data, row, label_width)
            if extra_detail_rows:
                extra_style.append(('FONT',
                                    (0, row_count + extra_rows + 1),
                                    (0, row_count + extra_rows + extra_detail_rows),
                                     self.styleDetail.fontName))
                extra_style.append(('TEXTCOLOR',
                                    (0, row_count + extra_rows + 1),
                                    (0, row_count + extra_rows + extra_detail_rows),
                                     self.styleDetail.textColor))
            extra_rows += extra_detail_rows

        self.add_row_table(data, row_count + extra_rows, extra_style)
        self.story.append(Spacer(self.doc.width, self.space_before_footer))
コード例 #51
0
ファイル: models.py プロジェクト: ewe2/G2
 def _add_emoticons(self, text):
     text = force_escape(text)
     text = text.split()
     emoticons = Emoticon.objects.filter(text__in=text)
     for i, word in enumerate(text):
         for e in emoticons:
             if e.text == word:
                 text[i] = "<img src='%s' alt='%s' title='%s' />" % (
                     "emoticons/" + e.filename, e.alt_text, e.text)
                 break
     return " ".join(text)
コード例 #52
0
ファイル: views.py プロジェクト: itsbenweeks/Amara
def get_team_attributes_for_editor(video):
    team_video = video.get_team_video()
    if team_video:
        team = team_video.team
        return dict([('teamName', team.name),
                     ('guidelines',
                      dict([(s.key_name.split('_', 1)[-1],
                             linebreaks(urlize(force_escape(s.data))))
                            for s in team.settings.guidelines()
                            if s.data.strip()]))])
    else:
        return None
コード例 #53
0
ファイル: pdf.py プロジェクト: firesalp/aemanager
 def add_row_detail(self, data, row, label_width):
     extra_rows = 0
     if row.detail:
         for line in row.detail.split("\n"):
             para = Paragraph(force_escape(line), self.styleDetail)
             para.width = label_width
             splitted_para = para.breakLines(label_width)
             for detail_row in splitted_para.lines:
                 detail = self.get_splitted_content(detail_row)
                 data.append((detail,))
                 extra_rows += 1
     return extra_rows
コード例 #54
0
def tooltip(value, max_length=None):
    """
    Adds tooltip mechanism to the given value by
    embracing it with 'span' tag with proper class.
    If `max_length` parameter is given, value
    would be chopped down to the given length and
    three dots would be added.
    See ``common.js`` file (located within media
    directory) for details how tooltips are created
    with javascript.
    """
    if max_length:
        max_length = int(max_length)
        output = value[:max_length]
        if len(value) > max_length:
            output += '...'
    else:
        output = value
    value = force_escape(value)
    output = force_escape(output)
    output = '<span class="show-tipsy" title="%s">%s</span>' % (value, output)
    return mark_safe(output)
コード例 #55
0
def full_img_tag(img):
    """
    Gives out an img tag that uses the full-res version of an Image.
    """
    try:
        if img.__class__ is Content:
            img = img.child
        disp_url = img.absolute_url()
        title = filter.force_escape(getattr(img, 'img_title', ''))
        tag = '<img src="%s" title="%s" alt="%s" />' % (disp_url, title, title)
        return mark_safe(tag)
    except:
        return ''