Python django.utils.safestring.mark_safe() Examples

The following are 30 code examples for showing how to use django.utils.safestring.mark_safe(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.safestring , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: order.py    License: 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 2
Project: Servo   Author: fpsw   File: base.py    License: 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
Project: Servo   Author: fpsw   File: base.py    License: 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
Project: django-fontawesome   Author: redouane   File: widgets.py    License: 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
Project: crowdata   Author: crowdata   File: admin.py    License: 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
Project: donation-tracker   Author: GamesDoneQuick   File: bid.py    License: 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 7
Project: donation-tracker   Author: GamesDoneQuick   File: views.py    License: 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 8
Project: django-usersettings2   Author: mishbahr   File: admin.py    License: 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 9
Project: coursys   Author: sfu-fas   File: mc.py    License: 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 10
Project: coursys   Author: sfu-fas   File: views.py    License: 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 11
Project: coursys   Author: sfu-fas   File: form_display.py    License: 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 12
Project: coursys   Author: sfu-fas   File: form_display.py    License: 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 13
Project: coursys   Author: sfu-fas   File: search_display.py    License: 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 14
Project: coursys   Author: sfu-fas   File: course_display.py    License: 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 15
Project: coursys   Author: sfu-fas   File: models.py    License: 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 16
Project: coursys   Author: sfu-fas   File: select.py    License: 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 17
Project: coursys   Author: sfu-fas   File: views.py    License: 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 18
Project: Servo   Author: fpsw   File: base.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def render(self, name, value, attrs=None):

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

        output = format_html(u'''
         <div class="input-group">
            {1}
             <span class="input-group-btn">
                <button class="btn btn-default" type="button"><i class="glyphicon glyphicon-search"></i></button>
            </span>
        </div>
        ''', flatatt(final_attrs), field)

        return mark_safe(output) 
Example 19
Project: Servo   Author: fpsw   File: servo_tags.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def markdown(text):
    import markdown
    result = markdown.markdown(text)
    return safestring.mark_safe(result) 
Example 20
Project: djreservation   Author: luisza   File: admin.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list_of_products(self, instance):

        return mark_safe(render_to_string(
            'djreservation/product_admin_reservation.html',
            {"instance": instance}
        )) 
Example 21
Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def document_count(self, obj):
        l = '<a href="%s?document_set__id=%s">%s</a>' % (reverse("admin:crowdataapp_document_changelist"),
                                                           obj.pk,
                                                           obj.documents.count())
        return mark_safe(l) 
Example 22
Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def user_link(self, obj):
        url = reverse('admin:auth_user_change', args=(obj.user.id,))
        return mark_safe('<a href="%s">%s</a>' % (url, obj.user.get_full_name())) 
Example 23
Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def document_link(self, obj):
        url = reverse('admin:crowdataapp_document_change', args=(obj.document.id,))
        return mark_safe('<a href="%s">%s</a>' % (url, obj.document.name)) 
Example 24
Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def document_set_link(self, obj):
        url = reverse('admin:crowdataapp_documentset_change', args=(obj.document.document_set.id,))
        return mark_safe('<a href="%s">%s</a>' % (url, obj.document.document_set.name)) 
Example 25
Project: donation-tracker   Author: GamesDoneQuick   File: lookups.py    License: Apache License 2.0 5 votes vote down vote up
def format_item_display(self, obj):
        result = '<a href="{0}">{1}</a>'.format(
            reverse(
                'admin:tracker_{0}_change'.format(obj._meta.model_name), args=[obj.pk]
            ),
            escape(str(obj)),
        )
        return mark_safe(result) 
Example 26
Project: donation-tracker   Author: GamesDoneQuick   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def target_object(self, instance):
        if instance.is_deletion():
            return 'Deleted'
        else:
            return mark_safe(
                '<a href="{0}">{1}</a>'.format(
                    instance.get_admin_url(), instance.object_repr
                )
            ) 
Example 27
Project: donation-tracker   Author: GamesDoneQuick   File: prize.py    License: Apache License 2.0 5 votes vote down vote up
def process_prize_submissions(request):
        currentEvent = viewutil.get_selected_event(request)
        return render(
            request,
            'admin/process_prize_submissions.html',
            {
                'currentEvent': currentEvent,
                'apiUrls': mark_safe(json.dumps(api_urls())),
            },
        ) 
Example 28
Project: donation-tracker   Author: GamesDoneQuick   File: bid.py    License: Apache License 2.0 5 votes vote down vote up
def process_pending_bids(request):
        currentEvent = viewutil.get_selected_event(request)
        return render(
            request,
            'admin/process_pending_bids.html',
            {
                'currentEvent': currentEvent,
                'apiUrls': mark_safe(json.dumps(api_urls())),
            },
        ) 
Example 29
Project: donation-tracker   Author: GamesDoneQuick   File: donation.py    License: Apache License 2.0 5 votes vote down vote up
def read_donations(request):
        currentEvent = viewutil.get_selected_event(request)
        return render(
            request,
            'admin/read_donations.html',
            {
                'currentEvent': currentEvent,
                'apiUrls': mark_safe(json.dumps(api_urls())),
            },
        ) 
Example 30
Project: donation-tracker   Author: GamesDoneQuick   File: inlines.py    License: Apache License 2.0 5 votes vote down vote up
def edit_link(self, instance):
        if instance.id is not None:
            url = reverse(
                'admin:{label}_{merge}_change'.format(
                    label=instance._meta.app_label, merge=instance._meta.model_name
                ),
                args=[instance.id],
            )
            return mark_safe('<a href="{u}">Edit</a>'.format(u=url))
        else:
            return mark_safe('Not Saved Yet')