Python django.utils.safestring.mark_safe() Examples

The following are 30 code examples of django.utils.safestring.mark_safe(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.safestring , or try the search function .
Example #1
Source File: form_display.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def field_display(field, safe=False):
    out = []
    if isinstance(field.field.widget, (forms.widgets.RadioSelect, forms.widgets.CheckboxSelectMultiple)):
        out.append('<div class="field radio">%s</div>' % (str(field)))
    else:
        out.append('<div class="field">%s</div>' % (str(field)))
    out.append(str(field.errors))

    if field.help_text:
        if isinstance(field.help_text, Promise):
            out.append('<div class="helptext">%s</div>' % (escape(field.help_text)))
        else:
            if safe:
                out.append('<div class="helptext">%s</div>' % (field.help_text))
            else:
                out.append('<div class="helptext">%s</div>' % (escape(field.help_text)))
    return mark_safe('\n'.join(out)) 
Example #2
Source File: base.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render(self, name, value, attrs=None):

        date_format = "yyyy-MM-dd"

        if "format" not in self.attrs:
            attrs['format'] = date_format

        if "data-format" not in self.attrs:
            attrs['data-format'] = date_format

        field = super(DatepickerInput, self).render(name, value, attrs)
        final_attrs = self.build_attrs(attrs)

        output = format_html(u'''
         <div class="input-append date datepicker" data-provide="datepicker" {0}>
            {1}
            <span class="add-on">
                <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
            </span>
        </div>
        ''', flatatt(final_attrs), field)

        return mark_safe(output) 
Example #3
Source File: base.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render(self, name, value, attrs=None):

        date_format = "yyyy-MM-dd hh:mm"

        if "data-format" not in self.attrs:
            attrs['data-format'] = date_format
        if "class" not in self.attrs:
            attrs['class'] = 'input-medium'

        field = super(DateTimePickerInput, self).render(name, value, attrs)
        final_attrs = self.build_attrs(attrs)

        output = format_html(u'''
         <div class="input-append date datetimepicker" {0}>
            {1}
            <span class="add-on">
                <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
            </span>
        </div>
        ''', flatatt(final_attrs), field)

        return mark_safe(output) 
Example #4
Source File: widgets.py    From django-fontawesome with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render_option(self, selected_choices, option_value, option_label):
            if option_value is None:
                option_value = ''
            option_value = force_text(option_value)
            if option_value in selected_choices:
                selected_html = mark_safe(' selected="selected"')
                if not self.allow_multiple_selected:
                    # Only allow for a single selection.
                    selected_choices.remove(option_value)
            else:
                selected_html = ''
            return format_html('<option data-icon="{0}" value="{0}"{1}>{2}</option>',
                option_value,
                selected_html,
                force_text(option_label),
            ) 
Example #5
Source File: admin.py    From crowdata with MIT License 6 votes vote down vote up
def answers(self, obj):
        field_template = "<li><input type=\"checkbox\" data-change-url=\"%s\" data-field-entry=\"%d\" data-document=\"%d\" data-entry-value=\"%s\" %s><span class=\"%s\">%s</span>: <strong>%s</strong> - <em>%s</em></li>"
        rv = '<ul>'
        form_fields = obj.form.fields.order_by('id').all()
        rv += ''.join([field_template % (reverse('admin:document_set_field_entry_change', args=(obj.document.pk, e.pk,)),
                                         e.pk,
                                         obj.document.pk,
                                         e.value,
                                         'checked' if e.verified else '',
                                         'verify' if f.verify else '',
                                         f.label,
                                         e.value,
                                         e.assigned_canonical_value())
                       for f, e in zip(form_fields,
                                       obj.fields.order_by('field_id').all())])
        rv += '</ul>'

        return mark_safe(rv) 
Example #6
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def accessories(request, pk, device_id):
    from django.utils import safestring

    if request.POST.get('name'):
        a = Accessory(name=request.POST['name'])
        a.order_id = pk
        a.device_id = device_id
        a.save()

    choice_list = []
    choices = Accessory.objects.distinct('name')

    for c in choices:
        choice_list.append(c.name)

    action = reverse('orders-accessories', args=[pk, device_id])
    selected = Accessory.objects.filter(order_id=pk, device_id=device_id)
    choices_json = safestring.mark_safe(json.dumps(choice_list))

    return render(request, 'devices/accessories_edit.html', locals()) 
Example #7
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def render_column(self, offering, column):
        if column == 'coursecode':
            txt = '%s\u00a0%s\u00a0%s' % (offering.subject, offering.number, offering.section) # those are nbsps
            url = reverse('browse:browse_courses_info', kwargs={'course_slug': offering.slug})
            col = mark_safe('<a href="%s">%s</a>' % (url, conditional_escape(txt)))
        elif column == 'instructors':
            col = offering.instructors_printing_str()
        elif column == 'campus':
            col = CAMPUSES_SHORT[offering.campus]
        elif column == 'enrol':
            col = '%i/%i' % (offering.enrl_tot, offering.enrl_cap)
            if offering.wait_tot:
                col += ' (+%i)' % (offering.wait_tot,)
        elif column == 'semester':
            col = str(offering.semester).replace(' ', '\u00a0') # nbsp
        elif hasattr(offering, 'get_%s_display' % column):
            # it's a choice field
            col = getattr(offering, 'get_%s_display' % column)()
        else:
            col = str(getattr(offering, column))
        
        return conditional_escape(col) 
Example #8
Source File: bid.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def parent_(self, obj):
        targetObject = None
        if obj.parent:
            targetObject = obj.parent
        elif obj.speedrun:
            targetObject = obj.speedrun
        elif obj.event:
            targetObject = obj.event
        if targetObject:
            return mark_safe(
                '<a href={0}>{1}</a>'.format(
                    str(viewutil.admin_url(targetObject)), targetObject
                )
            )
        else:
            return '<None>' 
Example #9
Source File: views.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def index(request, **kwargs):
    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../ui-tracker.manifest.json')
        ),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.tracker,
            'CONSTANTS': mark_safe(json.dumps(constants())),
            'ROOT_PATH': reverse('tracker:ui:index'),
            'app': 'TrackerApp',
            'form_errors': {},
            'props': '{}',
        },
    ) 
Example #10
Source File: models.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def html_contents(self, offering=None):
        """
        Return the HTML version of this version's wikitext (with macros substituted if available)

        offering argument only required if self.page isn't set: used when doing a speculative conversion of unsaved content.
        
        Cached to save frequent conversion.
        """
        key = self.html_cache_key()
        html = cache.get(key)
        if html:
            return mark_safe(html)
        else:
            markup_content = self.substitute_macros(self.get_wikitext())
            html = markup_to_html(markup_content, self.markup(), pageversion=self, html_already_safe=True)
            cache.set(key, html, 24*3600) # expired if activities are changed (in signal below), or by saving a PageVersion in this offering
            return mark_safe(html)


# signal for cache invalidation 
Example #11
Source File: course_display.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def display_form_as_row(form, arg=None):
    """
    Convert the form to a HTML table row
    set arg to be "deleted_flag" to include the deleted field
    """
    output = ["<tr>"]
    if arg == 'hidden':
        output = ['<tr class="hidden">']
    for field in form.visible_fields():
        if field.name == "deleted" and (arg != "deleted_flag"):
            output.append("<td></td>")
            continue
        c = Context({"field":field})
        output.append( FIELD_AS_TD_TEMPLATE.render(c))
    
    for field in form.hidden_fields():
        c = Context({"field":field})
        output.append( FIELD_AS_TD_TEMPLATE_HIDDEN.render(c))
    
    output.append("</tr>")
    
    return mark_safe('\n'.join(output)) 


# from http://stackoverflow.com/questions/35948/django-templates-and-variable-attributes 
Example #12
Source File: mc.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def get_entry_field(self, questionanswer=None, student=None):
        options = self.version.config.get('options', [])
        permute = self.version.config.get('permute', 'keep')
        show_no_answer = self.version.config.get('show_no_answer', 'noshow')
        if questionanswer:
            initial = questionanswer.answer.get('data', MultipleChoice.NA)
        else:
            initial = MultipleChoice.NA

        options = list(enumerate(options))  # keep original positions so the input values match that, but students see a possibly-randomized order

        if student and permute == 'permute':
            rand = self.question.quiz.random_generator(str(student.id) + '-' + str(self.question.id) + '-' + str(self.version.id))
            options = rand.permute(options)
        elif student and permute == 'not-last':
            rand = self.question.quiz.random_generator(str(student.id) + '-' + str(self.question.id) + '-' + str(self.version.id))
            last = options[-1]
            options = rand.permute(options[:-1])
            options.append(last)

        choices = [
            (OPTION_LETTERS[opos], mark_safe('<span class="mc-letter">' + OPTION_LETTERS[i] + '.</span> ') + escape(o[0]))
            for i, (opos, o)
            in enumerate(options)
        ]

        if show_no_answer == 'show':
            choices.append((MultipleChoice.NA, 'no answer'))

        field = forms.ChoiceField(required=False, initial=initial, choices=choices, widget=forms.RadioSelect())
        field.widget.attrs.update({'class': 'multiple-choice'})
        return field 
Example #13
Source File: mc.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def question_preview_html(self):
        # override to present options (original order) along with question text
        options = self.version.config.get('options', [])
        permute = self.version.config.get('permute', 'keep')
        q_html = self.question_html()
        choices_html = [
            '<p><span class="mc-letter">%s.</span> %s</p>' % (OPTION_LETTERS[i], escape(o[0]))
            for i, o
            in enumerate(options)
        ]

        if permute == 'keep':
            order_note = ''
        else:
            order_note = ' <span class="helptext">[Choices may have been presented in a different order during the quiz.]</span> '

        return mark_safe(''.join((
            '<div>',
            q_html,
            order_note,
            ''.join(choices_html),
            '</div>'
        ))) 
Example #14
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def edit_attach(request, course_slug, case_slug):
    """
    Front page of the file attachments interface
    """
    course = get_object_or_404(CourseOffering, slug=course_slug)
    case = get_object_or_404(DisciplineCaseBase, slug=case_slug, offering__slug=course_slug)
    case = case.subclass()
    attach_pub = CaseAttachment.objects.filter(case=case, public=True)
    attach_pri = CaseAttachment.objects.filter(case=case, public=False)

    if not case.can_edit('attach'):
        # once case is closed, don't allow editing
        return ForbiddenResponse(request)

    groupmembersJSON = case.groupmembersJSON()
    context = {'course': course, 'case': case, 'attach_pub': attach_pub, 'attach_pri': attach_pri,
            'templatesJSON': '[]', 'groupmembersJSON': mark_safe(groupmembersJSON)}
    return render(request, "discipline/show_attach.html", context) 
Example #15
Source File: search_display.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def score_stars(score, maxscore):
    """
    Turn the results score into 5 stars out of the max
    """
    stars = 1.0 * STARS * score/maxscore
    wholestars = int(stars)

    frac = stars - wholestars
    if frac >= 0.5:
        halfstars = 1
    else:
        halfstars = 0

    return mark_safe(
        wholestars * '<i class="fa fa-star"></i>'
        + halfstars * '<i class="fa fa-star-half"></i>'
        + (STARS - wholestars - halfstars) * '<i class="fa fa-star-o"></i>'
    ) 
Example #16
Source File: form_display.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def label_display(field, prefix=''):
    out = []

    labelid = str(field.name)
    if prefix:
        labelid = prefix + '-' + labelid
    if isinstance(field.field.widget, (RadioSelect, SupervisorWidget)):
        labelid += '_0'

    out.append('<label for="id_%s">' % (labelid,))
    out.append(escape(field.label))
    out.append(':')
    if field.field.required or (hasattr(field.field, 'force_display_required') and field.field.force_display_required):
        out.append('&nbsp;' + required_icon)

    out.append('</label>')

    return mark_safe(''.join(out)) 
Example #17
Source File: admin.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_select_site_form(self, request, context, form_url=''):
        """
        Render the site choice form.
        """
        app_label = self.opts.app_label
        context.update({
            'has_change_permission': self.has_change_permission(request),
            'form_url': mark_safe(form_url),
            'opts': self.opts,
            'add': True,
            'save_on_top': self.save_on_top,
        })

        return render_to_response(self.select_site_form_template or [
            'admin/%s/%s/select_site_form.html' % (app_label, self.opts.object_name.lower()),
            'admin/%s/select_site_form.html' % app_label,
            'admin/usersettings/select_site_form.html',  # added default here
            'admin/select_site_form.html'
        ], context) 
Example #18
Source File: select.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def to_html(self, fieldsubmission=None):

        the_choices = [(k, v) for k, v in self.config.items() if k.startswith("choice_") and self.config[k]]
        the_choices = sorted(the_choices, key=lambda choice: (int) (re.findall(r'\d+', choice[0])[0]))

        initial = []

        if fieldsubmission:
            initial = fieldsubmission.data['info']

        display_values = [dict(the_choices)[str(i)] for i in initial]

        if display_values:
            output = '<ul>'

            for item in display_values:
                output += '<li>%s</li>' % escape(str(item))
            output += '</ul>'
        else:
            output = '<p class="empty">None selected</p>'

        return mark_safe(output) 
Example #19
Source File: form_display.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def required_label(label):
    """
    Style label as it should be if on a required field.
    """
    return mark_safe(escape(label) + '&nbsp;' + required_icon) 
Example #20
Source File: course_display.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def error_note(form):
    """
    Display the pre-form note about errors (if any).
    """
    output = ""
    if form.errors:
        c = Context({})
        output = ERROR_NOTE_TEMPLATE.render(c)

    return mark_safe(output) 
Example #21
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def _forbidden_response(request, visible_to):
    """
    A nicer forbidden message that says why, and gently suggests that anonymous users log in.
    """
    error = 'Not allowed to view this page. It is visible only to %s in this course.' % (visible_to,)
    errormsg_template = '<strong>You are not currently logged in</strong>. You may be able to view this page if you <a href="%s">log in</a>'
    errormsg = None
    if not request.user.is_authenticated:
        url = conditional_escape(settings.LOGIN_URL + '?next=' + request.get_full_path())
        errormsg = mark_safe(errormsg_template % (url))

    return HttpError(request, status=403, title="Forbidden", error=error, errormsg=errormsg) 
Example #22
Source File: markup.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def sanitize_html(html, restricted=False):
    """
    Sanitize HTML we got from the user so it's safe to include in the page
    """
    # TODO: document the HTML subset allowed (particularly <pre lang="python">)
    allowed = allowed_tags_restricted if restricted else allowed_tags
    return mark_safe(bleach.clean(html, tags=allowed, attributes=allowed_attributes, strip=True)) 
Example #23
Source File: form_display.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def as_dl(form, safe=False, excludefields=[], includefields=None, formclass='dlform', reqmessage=True):
    """
    Output a Form as a nice <dl>
    """
    out = []
    # if the form has any widgets that have Media elements, include this
    out.append(str(form.media))
    out.append(str(form.non_field_errors()))
    if form.hidden_fields():
        out.append('<div style="display:none">')
        for field in form.hidden_fields():
            if field.name in excludefields or (
                    includefields is not None and field.name not in includefields) :
                continue
            out.append(str(field))
        out.append('</div>')
        
    out.append('<dl class="%s">' % (formclass))
    reqcount = 0
    for field in form.visible_fields():
        if field.name in excludefields or (
                includefields is not None and field.name not in includefields) :
            continue

        if field.field.required:
            reqcount += 1
        
        if field.label:
            out.append('<dt>%s</dt>' % (label_display(field, form.prefix)))

        out.append('<dd>')
        out.append(field_display(field, safe=safe))
        out.append('</dd>')
    
    out.append('</dl>')
    if reqmessage and reqcount > 0:
        out.append(required_message(None))
    return mark_safe('\n'.join(out)) 
Example #24
Source File: auth.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def ForbiddenResponse(request, errormsg=None, exception=None):
    error = mark_safe("You do not have permission to access this resource.")
    if not request.user.is_authenticated:
        login_url = settings.LOGIN_URL + '?' + urllib.parse.urlencode({'next': request.get_full_path()})
        error += mark_safe(' You are <strong>not logged in</strong>, so maybe <a href="%s">logging in</a> would help.' % (login_url))
    return HttpError(request, status=403, title="Forbidden", error=error, errormsg=errormsg) 
Example #25
Source File: text.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def to_html(self, fieldsubmission=None):
        return mark_safe('<p>' + escape(self.to_text(fieldsubmission)) + '</p>') 
Example #26
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        return mark_safe('<hr />')


# Manage groups 
Example #27
Source File: text.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def to_html(self, fieldsubmission=None):
        return mark_safe('<p>' + linebreaksbr(fieldsubmission.data['info'], autoescape=True) + '</p>') 
Example #28
Source File: text.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def to_html(self, fieldsubmission=None):
        return mark_safe('<p>' + linebreaksbr(fieldsubmission.data['info'], autoescape=True) + '</p>') 
Example #29
Source File: text.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def to_html(self, fieldsubmission=None):
        return mark_safe('<p>' + linebreaksbr(fieldsubmission.data['info'], autoescape=True) + '</p>') 
Example #30
Source File: models.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def email_mailto(self):
        "A mailto: URL for this person's email address: handles the case where we don't know an email for them."
        email = self.email()
        if email:
            return mark_safe('<a href="mailto:%s">%s</a>' % (escape(email), escape(email)))
        else:
            return "None"