示例#1
0
def format_post_list(
        context, detail_object, *args, **kwargs):
    request = context.get('request')
    opposite = kwargs.get('opposite')
    perm_button = kwargs.get('perm_button')
    future_perms = request.user.has_perm(
        'blog.view_future_post')
    if future_perms:
        post_list = detail_object.blog_posts.all()
    else:
        post_list = detail_object.blog_posts.published()
    if opposite is None:
        section_attr = ''
    elif opposite or perm_button:
        section_attr = mark_safe(
            'class="meta one-third column"')
    else:  # opposite is an empty list
        section_attr = mark_safe(
            'class="meta offset-by-two '
            'two-thirds column"')
    return {
        'section_attr': section_attr,
        'post_list': post_list.values(
            'title', 'slug', 'pub_date'),
    }
示例#2
0
def display_cell(cell):
    if cell.cell_type == Cell.Type.TEXT:
        return mark_safe(cell.content)
    if cell.cell_type == Cell.Type.IMAGE:
        try:
            cell_image = CellImage.objects.get(cell=cell)
            if cell_image.image:
                url = '%s%s' % (settings.MEDIA_URL, cell_image.image)
                return mark_safe('<img src="%s" alt=""/>' % url)
        except CellImage.DoesNotExist:
            pass
        return '--'
示例#3
0
    def render(self, name, value, attrs=None):
        """ Render the button.
        
        If given an ``onClick`` attribute, id of the widget will be passed in to
        the function parameters.
        
        :param name: The name of the widget
        :type name: str
        
        :param value: The value of the widget (unused).
        :type value: void
        
        :param attrs: Attributes for the widget.
        :type attrs: dict
        """
        if 'id' in attrs and self.on_click_method:
            attrs.update({
                'onClick' : str(self.on_click_method%{'id' : attrs['id'],}),
                'type' : 'button',
            })
            
        # It's ugly, but first we need to prepend some javascript.
        js = static(STATIC_JS)
        
        logger.debug(js)
        
        s = """<script type="text/javascript"></script>
<script type="text/javascript" src="%s"></script>"""%js
        
        return mark_safe(s + "<button %s>%s</button>"%(html_attrs(attrs),
                                                   self.label))
示例#4
0
 def order(self, obj):
     if obj.order_line:
         order = obj.order_line.parent_object
         return mark_safe('<a href="%s">%s</a>' % (
             reverse('admin:checkout_order_change', args=(order.pk, )),
             order))
     return ''
def format_post_list(context, detail_object, *args, **kwargs):
    request = context.get("request")
    opposite = kwargs.get("opposite")
    perm_button = kwargs.get("perm_button")
    future_perms = request.user.has_perm("blog.view_future_post")
    if future_perms:
        post_list = detail_object.blog_posts.all()
    else:
        post_list = detail_object.blog_posts.published()
    if opposite is None:
        section_attr = ""
    elif opposite or perm_button:
        section_attr = mark_safe('class="meta one-third column"')
    else:  # opposite is an empty list
        section_attr = mark_safe('class="meta offset-by-two ' 'two-thirds column"')
    return {"section_attr": section_attr, "post_list": post_list.values("title", "slug", "pub_date")}
示例#6
0
    def render(self):
        content = self.get_content()
        for reference in self.references.all():
            content = reference.update_references(content)

        return mark_safe(
            self._meta.app_config.markdown_parser.convert(content))
示例#7
0
    def video_tag(self, attrs=None):
        if attrs is None:
            attrs = {}
        else:
            attrs = attrs.copy()
        if self.thumbnail:
            attrs['poster'] = self.thumbnail.url

        transcodes = self.transcodes.exclude(processing=True).filter(
            error_message__exact='')
        sources = []
        for transcode in transcodes:
            sources.append("<source src='{0}' type='video/{1}' >".format(
                transcode.url, transcode.media_format.name))

        mime = mimetypes.MimeTypes()
        sources.append("<source src='{0}' type='{1}'>".format(
            self.url,
            mime.guess_type(self.url)[0]))

        sources.append(
            "<p>Sorry, your browser doesn't support playback for this video</p>"
        )
        return mark_safe("<video {0}>\n{1}\n</video>".format(
            flatatt(attrs), "\n".join(sources)))
示例#8
0
 def lobbyists(self, obj):
     if obj.latest_data:
         return mark_safe(', '.join([
             u'<a href="/admin/lobbyists/lobbyist/' + unicode(lobbyist.pk) +
             '/">' + unicode(lobbyist) + u'</a>'
             for lobbyist in obj.latest_data.lobbyists.all()
         ]))
示例#9
0
文件: admin.py 项目: hide77/zt_mass
 def modify(self, obj):
     if obj.pk:
         href = obj.get_admin_url()
         attrs = 'href="%s" target="_blank" class="changelink"' % href
         return mark_safe('<a %s>Modify</a >' % attrs)
     else:
         return '-'
示例#10
0
 def __init__(self, *args, **kwargs):
     self.bike = kwargs.pop("bike", None)
     is_ajax = kwargs.pop("is_ajax", None)
     action = kwargs.pop("action", None)
     super().__init__(*args, **kwargs)
     self.instance.gallery = self.bike.picture_gallery
     self.helper = FormHelper()
     if action is not None:
         self.helper.form_action = action
     self.helper.layout = layout.Layout(
         layout.Field("image"),
     )
     form_id = "bikePictureForm"
     self.helper.form_id = form_id
     if not is_ajax:
         self.helper.layout.append(
             bootstrap.FormActions(
                 bootstrap.StrictButton(
                     mark_safe('<i class="fa fa-upload"></i> ') + _(
                         "Upload picture"),
                     type="submit",
                     form=form_id,
                     css_class="btn btn-primary"
                 ),
             )
         )
示例#11
0
文件: promgen.py 项目: xinbuq/promgen
 def to_tag():
     yield '<ol class="breadcrumb">'
     for href, text in generator():
         yield format_html('<li><a href="{}">{}</a></li>', mark_safe(href), text)
     if label:
         yield format_html('<li class="active">{}</li>', label)
     yield "</ol>"
示例#12
0
def format_urn(obj):
    """
    Re-format a standardised URN with any slashes or extra characters
    re-inserted.
    """
    formatted_urn = format_for_region(obj)
    return mark_safe(formatted_urn)
示例#13
0
文件: promgen.py 项目: xinbuq/promgen
def breadcrumb(instance, label=None):
    """
    Create HTML Breadcrumb from instance

    Starting with the instance, walk up the tree building a bootstrap3
    compatiable breadcrumb
    """
    from promgen import models

    def shard(obj):
        yield obj.get_absolute_url(), obj.name

    def service(obj):
        yield from shard(obj.shard)
        yield obj.get_absolute_url(), obj.name

    def project(obj):
        yield from service(obj.service)
        yield obj.get_absolute_url(), obj.name

    def rule(obj):
        if obj.content_type.model == "site":
            yield reverse("rules-list"), "Common Rules"
        if obj.content_type.model == "service":
            yield from service(obj.content_object)
        if obj.content_type.model == "project":
            yield from project(obj.content_object)
        # If we have a new rule, it won't have a name
        if obj.pk:
            yield obj.get_absolute_url(), obj.name

    def sender(obj):
        if obj.content_type.model == "service":
            yield from service(obj.content_object)
        if obj.content_type.model == "project":
            yield from project(obj.content_object)

    def generator():
        yield reverse("home"), "Home"
        if isinstance(instance, models.Sender):
            yield from sender(instance)
        if isinstance(instance, models.Project):
            yield from project(instance)
        if isinstance(instance, models.Service):
            yield from service(instance)
        if isinstance(instance, models.Shard):
            yield from shard(instance)
        if isinstance(instance, models.Rule):
            yield from rule(instance)

    def to_tag():
        yield '<ol class="breadcrumb">'
        for href, text in generator():
            yield format_html('<li><a href="{}">{}</a></li>', mark_safe(href), text)
        if label:
            yield format_html('<li class="active">{}</li>', label)
        yield "</ol>"

    return mark_safe("".join(to_tag()))
示例#14
0
文件: admin.py 项目: hide77/zt_mass
 def delete(self, obj):
     if obj.pk:
         href = self.get_delete_url(obj)
         next_url = self.get_delete_next_url(obj)
         attrs = 'href="%s?next=%s" class="deletelink"' % (href, next_url)
         return mark_safe('<a %s>Delete</a>' % attrs)
     else:
         return '-'
示例#15
0
def jsonify(object):
    jsonified = jsonify_html(object)

    # Allow for safe embedding in <script> tags,
    # see http://stackoverflow.com/questions/4176511/embedding-json-objects-in-script-tags
    jsonified = jsonified.replace('<', '\\u003c').replace('>', '\\u003e')

    return mark_safe(jsonified)
示例#16
0
def set_defaults(config):
    config.setdefault('leaflet', {})
    config['leaflet'].setdefault('tilesURL', 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'),
    config['leaflet'].setdefault('default_position', {'lat': 30.0, 'lng': -40.0, 'zoom': 3})
    config['leaflet'].setdefault('id', 'mapbox.streets'),
    config['leaflet'].setdefault('maxZoom', 18),
    config['leaflet'].setdefault('detectRetina', True)
    config['leaflet'].setdefault('attribution', mark_safe('Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a>')),
示例#17
0
 def __init__(self, *args, **kwargs):
     super(RegistrationForm, self).__init__(*args, **kwargs)
     if not newsletter.is_enabled():
         del self.fields['subscribe']
     else:
         self.fields['subscribe'].help_text = mark_safe(
             "We'd love to keep you updated via email with product and feature announcements, promotions, educational materials, and events. Our updates focus on relevant information and never sell your data to marketing companies. See our <a href=\"%(privacy_link)s\">Privacy Policy</a> for more details."
             .format(privacy_link=settings.PRIVACY_URL, ))
示例#18
0
def _clean_username(self, fn=getattr(AuthenticationForm, "clean_username", lambda self: self.cleaned_data['username'])):
    from django.contrib.auth import get_user_model
    username = self.cleaned_data.get('username')
    UserModel = get_user_model()
    if username and not UserModel.objects.filter(**{UserModel.USERNAME_FIELD: username}).exists():
        raise foo.ValidationError(mark_safe("That username is incorrect. If you forgot it, you can <a href='%s'>reset your password</a> (the password reset email contains your username)." % reverse("password_reset")), code="username")

    return fn(self)
示例#19
0
def render_notification_text(context, email_notification, email_type):
    text_context = context.get("text_context")

    if not text_context or not email_notification:
        return

    render_func = "render_%s" % email_type
    message = getattr(email_notification, render_func)(context=text_context)
    return mark_safe(message)
示例#20
0
def render_notification_text(context, email_notification, email_type):
    text_context = context.get('text_context')

    if not text_context or not email_notification:
        return

    render_func = 'render_%s' % email_type
    message = getattr(email_notification, render_func)(context=text_context)
    return mark_safe(message)
示例#21
0
    def get_profile(self, obj):
        try:
            profile = CorporateProfile.objects.get(company_name=obj)
            format_values = {
                'link':
                reverse('admin:accounts_corporateprofile_change',
                        args=[profile.pk]),
                'profile':
                _('Link')
            }

            return mark_safe(
                '<a href="{link}"><i class="icon-tick"></i> {profile}</a>'.
                format(**format_values))

        except CorporateProfile.DoesNotExist:
            return mark_safe(
                '<i class="icon-cross" style="color: #d49d9d;"></i>')
示例#22
0
文件: admin.py 项目: hide77/zt_mass
 def actions(self, obj):
     if obj.pk:
         href = reverse('admin:portfolio_uploadedfile_scanschema',
                        args=[obj.uploaded_file.portfolio.pk, obj.pk])
         attrs = 'href="%s" class="button" style="white-space:nowrap"' \
             % href
         return mark_safe('<a %s>Start File Schema Parsing Job</a>' % attrs)
     else:
         return '-'
示例#23
0
文件: admin.py 项目: hide77/zt_mass
 def actions(self, obj):
     if obj.pk:
         portfolio_id = obj.extract_job.mapping.file_schema_job.cleaned_file.uploaded_file.portfolio.pk
         href = reverse('admin:portfolio_populatejob_inference',
                        args=[portfolio_id, obj.pk])
         attrs = 'href="%s" class="button" style="white-space:nowrap"' % href
         return mark_safe('<a %s>Start inference job</a>' % attrs)
     else:
         return '-'
示例#24
0
    def get_company_name(self, obj):
        name = obj.company_name

        format_values = {
            'link': reverse('admin:accounts_companyname_change',
                            args=[name.pk])
        }

        return mark_safe('<a href="{link}">Link</a>'.format(**format_values))
示例#25
0
def paginate(context, object_list):
    """
    Creates a paginate function
    @type object_list: django.core.paginator.Page
    """

    template = env.get_template(PAGINATOR_TEMPLATE)
    paginate_dict = paginate_object_list(context['request'].GET.copy(), object_list)
    rendered_template = template.render(paginate_dict)
    return mark_safe(rendered_template)
示例#26
0
 def __init__(self, *args, **kwargs):
     super(RegistrationForm, self).__init__(*args, **kwargs)
     if not newsletter.is_enabled():
         del self.fields['subscribe']
     else:
         # NOTE: the text here is duplicated within the ``NewsletterConsent`` component
         # in the UI
         self.fields['subscribe'].help_text = mark_safe("We'd love to keep you updated via email with product and feature announcements, promotions, educational materials, and events. Our updates focus on relevant information and never sell your data to marketing companies. See our <a href=\"%(privacy_link)s\">Privacy Policy</a> for more details.".format(
             privacy_link=settings.PRIVACY_URL,
         ))
示例#27
0
    def get_sale_price(self):
        if self.sale_price is not None:
            html_text = """
                <span class='sale-price'>%s</span>
                <span class='og-price'>%s</span>
            """ % (self.sale_price, self.price)

        else:
            html_text = "<span class='price'>%s</span>" % self.price
        return mark_safe(html_text)
示例#28
0
    def get_html_price(self):
        if self.sale_price is not None:
            html_text = "<span class='sale-price'>%s </span>" % (
                self.sale_price)

            html_text += "<span class='og-price'>%s</span>" % (self.price)
        else:
            html_text = "<span class='price'>%s</span>" % (self.price)

        return mark_safe(html_text)
示例#29
0
def website_favicon(website):
    if website.favicon and website.favicon_cropping:
        href = website.favicon_url
        extension = str(website.favicon.name).split('.')[-1]
        image_type = 'image/%s' % extension
    else:
        href = settings.STATIC_URL + 'img/favicon.png'
        image_type = 'image/png'

    favicon_tmpl = '<link rel="shortcut icon" type="%s" href="%s" />'
    return mark_safe(favicon_tmpl % (image_type, href))
示例#30
0
 def get_creator(self, obj):
     user = obj.created_by
     if user:
         format_values = {
             'link': reverse('admin:accounts_user_change', args=[user.pk]),
             'email': user.email
         }
         return mark_safe(
             '<a href="{link}">{email}</a>'.format(**format_values))
     else:
         return '-'
示例#31
0
def wrap_action_name(action):
    verbose_name = action.verbose_name
    help_text = action.help_text
    if help_text:
        verbose_name = verbose_name + """
        &nbsp;<i
            data-tooltip
            class="has-tip fa fa-info-circle"
            title='{txt}'></i>
        """.format(txt=strip_tags(str(help_text)), )
    return mark_safe(verbose_name)
示例#32
0
 def render_form(self, *args, **kwargs):
     errors = kwargs.pop('errors')
     if errors:
         # Pretend the error is a readonly input so that we get nice formatting
         # Issue discussed here: https://github.com/wagtail/wagtail/issues/4122
         error_message = '<div class="error"><input readonly placeholder="{}"></div>'.format(
             errors[0])
     else:
         error_message = ''
     form = super().render_form(*args, **kwargs)
     form = '<br>'.join([self.description, form]) + error_message
     return mark_safe(form)
示例#33
0
 def clean_download_url(self):
     cl = self.cleaned_data['download_url'] or None
     if cl is not None:
         try:
             img = Image.objects.get(download_url=cl)
         except Image.DoesNotExist:
             pass
         else:
             raise forms.ValidationError(mark_safe(
                 ugettext('Image <a href="%(url)s">already in repository</a>.'
                     ) % {'url': img.get_absolute_url()}))
     return cl
示例#34
0
 def first_photo(self, obj):
     project_photos = obj.productphoto_set.all()[:1]
     if project_photos.count() > 0:
         photo_preview = render_to_string(
             "products/includes/photo-preview.html", {
                 "photo": project_photos[0],
                 "size": "100",
                 "product": obj,
                 "target": "preview",
             })
         return mark_safe(photo_preview)
     return ""
示例#35
0
    def __init__(self, *args, **kwargs):
        super(EventCreateStepFirstForm, self).__init__(*args, **kwargs)

        template_list = Template.objects.all()
        self.fields['template'].help_text = mark_safe(''.join([
            *[
                '<span class="template-file-href href-{}"><a href="{}">Скачать файл</a> с описанием экскурсии.</span>'
                .format(
                    t.id,
                    t.file.url,
                ) for t in template_list if t.file
            ]
        ]))
示例#36
0
    def get_email_content_for_admin_field(self):
        contents = []

        if self.email.body:
            contents.append('<textarea cols="150" rows="20">%s</textarea>' % self.email.body)

        for alternative in self.email.alternatives:
            if alternative[1] == 'text/html':
                contents.append('<textarea cols="150" rows="20">%s</textarea>' % alternative[0])
            else:
                contents.append('<code>Alternative in mime type: %s</code>' % alternative[1])

        return mark_safe('<hr />'.join(contents))
示例#37
0
    def get_email_content_for_admin_field(self):
        contents = []

        if self.email.body and self.email.body.strip():
            contents.append('<textarea cols="150" rows="20">%s</textarea>' % self.email.body)

        for alternative in self.email.alternatives:
            if alternative[1] == 'text/html':
                contents.append('<textarea cols="150" rows="20">%s</textarea>' % alternative[0])
            else:
                contents.append('<code>Alternative in mime type: %s</code>' % alternative[1])

        return mark_safe('<hr />'.join(contents))
def add_export_elements_classes(value):
    soup = BeautifulSoup(value, 'html.parser')
    mapping = [
        ('h1', 'heading-xlarge'),
        ('h2', 'heading-large'),
        ('h3', 'heading-medium'),
        ('ul', 'list list-bullet'),
        ('ol', 'list list-number'),
    ]
    for tag_name, class_name in mapping:
        for element in soup.findAll(tag_name):
            element.attrs['class'] = class_name
    return mark_safe(str(soup))
示例#39
0
    def render(self, context):
        request = context.get("request", None)

        if request:
            if self.option == "admin-only" and not request.user.is_staff:
                return ''

            if self.option == "auth-only" and not request.user.is_authenticated(
            ):
                return ''

        static_url = getattr(settings, 'STATIC_URL', '')
        url = '<link rel="stylesheet" href="{0}css/coop_bar.css?v={1}" type="text/css" />'.format(
            static_url, get_version())
        headers = [
            mark_safe(url),
            mark_safe(
                '<link rel="stylesheet" href="{0}fontawesome/css/all.css" type="text/css" />'
                .format(static_url))
        ]
        print("HEADERS: ", headers)
        headers += CoopBar().get_headers(request, context_to_dict(context))
        return "\n".join(headers)
def format_post_list(
        context, detail_object, *args, **kwargs):
    request = context.get('request')
    opposite = kwargs.get('opposite')
    future_perms = request.user.has_perm(
        'blog.view_future_post')
    if future_perms:
        post_list = detail_object.blog_posts.all()
    else:
        post_list = detail_object.published_posts
    if opposite is None:
        section_attr = ''
    elif opposite or future_perms:
        section_attr = mark_safe(
            'class="meta one-third column"')
    else:  # opposite is an empty list
        section_attr = mark_safe(
            'class="meta offset-by-two '
            'two-thirds column"')
    return {
        'section_attr': section_attr,
        'post_list': post_list,
    }
示例#41
0
    def render_media(self):
        cachekey = 'rendered_media_%s' % md5(self.url).hexdigest()
        rendered = cache.get(cachekey)

        if not rendered:
            rendered = (
                '<iframe width="100%%" height="60" '
                'src="https://www.mixcloud.com/widget/iframe/?feed=%s'
                '&hide_cover=1&mini=1&light=1" frameborder="0"></iframe>'
            ) % urlquote(self.url)

            cache.set(cachekey, rendered, 60 * 60 * 24)

        return mark_safe(rendered)
示例#42
0
文件: accounts.py 项目: yaoqi/sentry
 def __init__(self, *args, **kwargs):
     super(PasswordlessRegistrationForm, self).__init__(*args, **kwargs)
     if not newsletter.is_enabled():
         del self.fields['subscribe']
     else:
         # NOTE: the text here is duplicated within the ``NewsletterConsent`` component
         # in the UI
         notice = (
             "We'd love to keep you updated via email with product and feature "
             "announcements, promotions, educational materials, and events. "
             "Our updates focus on relevant information, and we'll never sell "
             "your data to third parties. See our "
             "<a href=\"{privacy_link}\">Privacy Policy</a> for more details."
         )
         self.fields['subscribe'].help_text = mark_safe(
             notice.format(privacy_link=settings.PRIVACY_URL))
示例#43
0
    def video_tag(self, attrs=None):
        if attrs is None:
            attrs = {}
        else:
            attrs = attrs.copy()
        if self.thumbnail:
            attrs['poster'] = self.thumbnail.url

        transcodes = self.transcodes.exclude(processing=True).filter(error_message__exact='')
        sources = []
        for transcode in transcodes:
            sources.append("<source src='{0}' type='video/{1}' >".format(transcode.url, transcode.media_format.name))

        mime = mimetypes.MimeTypes()
        sources.append("<source src='{0}' type='{1}'>"
                       .format(self.url, mime.guess_type(self.url)[0]))

        sources.append("<p>Sorry, your browser doesn't support playback for this video</p>")
        return mark_safe(
            "<video {0}>\n{1}\n</video>".format(flatatt(attrs), "\n".join(sources)))
 def render(self, name, value, attrs):
     html = super(SizeWidget, self).render(name, value, attrs)
     return mark_safe('<label for="%s">Size:</label>%s'%(name, html))
示例#45
0
 def get_name(self):
     name = self.name.format(url=self.url) if self.url else self.name
     html = markdown.markdown(name)
     return mark_safe(bleach.clean(html, strip=True, tags=['strong', 'a']))
示例#46
0
 def view(self, obj=None):
     return mark_safe(
         '<a href={}>view</a>'.format(reverse_lazy('resume:index', kwargs={'slug': obj.slug}))
     )
示例#47
0
import re
from collections import OrderedDict

from django.utils.text import mark_safe

from inloop.common.validators import RegexSyntaxValidator

config = OrderedDict()
config["SIGNUP_ALLOWED"] = (False, mark_safe("Allow or disallow new users to sign up."))
config["EMAIL_PATTERN"] = ("", mark_safe(
    "A Python regular expression used to test email addresses during sign up. The "
    "regex is compiled using <code>re.VERBOSE</code>, which means you can use "
    "comments and whitespace (which will be ignored) to structure the regex."), "regex"
)
config["EMAIL_HELP_TEXT"] = ("", mark_safe(
    "Form field help text with a human-friendly description of <code>EMAIL_PATTERN</code>."
))
config["EMAIL_ERROR_MESSAGE"] = ("", mark_safe(
    "Form field error message in case <code>EMAIL_PATTERN</code> doesn't match."
))

fieldsets = {
    "Signup form settings": ["SIGNUP_ALLOWED", "EMAIL_PATTERN",
                             "EMAIL_HELP_TEXT", "EMAIL_ERROR_MESSAGE"]
}

fields = {
    "regex": ["django.forms.CharField", {
        "widget": "django.forms.Textarea",
        "validators": [RegexSyntaxValidator(re.VERBOSE)],
        "required": False
示例#48
0
 def get_markdown(self):
     content = self.content
     return mark_safe(markdown(content))
示例#49
0
def render_form_widget(field, **kwargs):
    markup = field.as_widget(attrs=kwargs)
    return mark_safe(markup)
示例#50
0
 def lobbyists(self, obj):
     return mark_safe(', '.join([
         u'<a href="/admin/lobbyists/lobbyist/'+unicode(lobbyist.pk)+'/">'+unicode(lobbyist)+u'</a>' for lobbyist in obj.latest_data.lobbyists.all()
     ]))
示例#51
0
 def links(self, obj):
     return mark_safe(
         '<a href="%s">View order</a>' % obj.get_absolute_url())
def hdir(obj):
    """
    HTML version of dir.
    """
    dir_text = dir(obj)
    return mark_safe("<pre>{0}</pre>".format(dir_text))
示例#53
0
文件: admin.py 项目: theju/atifier
 def link(self, obj):
     url = obj.page.url
     return mark_safe('<a href="{0}" target="_blank">{0}</a>'.format(url))
示例#54
0
 def heading(self):
     return mark_safe(html_parser.unescape(self.glossary.get('heading', '')))
示例#55
0
def complete_profile_hint(sender, user, request, **kwargs):
    """Show logged in users a hint if they do not have a complete profile."""
    if not user_profile_complete(user):
        message = mark_safe(INCOMPLETE_HINT % reverse("accounts:profile"))
        # fail_silently needs to be set for unit tests using RequestFactory
        messages.warning(request, message, fail_silently=True)
示例#56
0
 def get_description(self):
     if not self.description:
         return ''
     desc = self.description.format(url=self.url) if self.url else self.description
     html = markdown.markdown(desc)
     return mark_safe(bleach.clean(html, strip=True, tags=['strong', 'a']))
示例#57
0
 def _html_description(self, obj):
     return mark_safe(obj._description)
    def render(self, name, value, attrs=None):
        """
        Renders this field into an HTML string.

        :param name: (str) name of the field
        :param value: (str) a json string of a two-tuple list automatically passed in by django
        :param attrs: (dict) automatically passed in by django (unused by this function)
        """
        if not value:
            value = '{}'

        if attrs is None:
            attrs = {}

        output = '<div class="djangocms-attributes-field">'
        if value and isinstance(value, dict) and len(value) > 0:
            for key in sorted(value):
                output += self._render_row(key, value[key], name, flatatt(self.key_attrs), flatatt(self.val_attrs))

        # Add empty template
        output += """
        <div class="template hidden">{0}
        </div>""".format(self._render_row('', '', name, flatatt(self.key_attrs), flatatt(self.val_attrs)))

        # Add "+" button
        output += """
        <div class="related-widget-wrapper">
            <a class="add-attributes-pair" href="#" title="{title}">
                <img src="{addIconSrc}" alt="{title}">
            </a>
        </div>
        """.format(
            title=_('Add another key/value pair'),
            addIconSrc=static('admin/img/icon-addlink.svg'),
        )
        output += '</div>'

        # NOTE: This is very consciously being inlined into the HTML because
        # if we use the Django "class Media()" mechanism to include this JS
        # behaviour, then every project that uses any package that uses Django
        # CMS Attributes Field will also have to add this package to its
        # INSTALLED_APPS. By inlining the JS and CSS here, we avoid this.
        output += """
        <style>
            .delete-attributes-pair,
            .add-attributes-pair {
                border: 1px solid #ddd;
                border-radius: 3px;
                display: inline-block;
                padding: 6px 10px 8px;
            }
            .delete-attributes-pair {
                margin-left: 16px;
            }
        </style>
        <script>
            (function ($) {
                function fixUpIds (fieldGroup) {
                    fieldGroup.find('.attributes-pair').each(function (idx, value) {
                        $(value).find('.attributes-key').attr('id', 'field-key-row-' + idx)
                                .siblings('label').attr('for', 'field-key-row-' + idx);
                        $(value).find('.attributes-value').attr('id', 'field-value-row-' + idx)
                                .siblings('label').attr('for', 'field-value-row-' + idx);
                    });
                }

                $(document).ready(function () {
                    $('.djangocms-attributes-field').each(function () {
                        var that = $(this);
                        var emptyRow = that.find('.template');
                        var btnAdd = that.find('.add-attributes-pair');
                        var btnDelete = that.find('.delete-attributes-pair');

                        btnAdd.on('click', function (event) {
                            event.preventDefault();
                            emptyRow.before(emptyRow.find('.attributes-pair').clone());
                            fixUpIds(that);
                        });

                        btnDelete.on('click', function (event) {
                            event.preventDefault();
                            $(this).parents('.attributes-pair').remove();
                            fixUpIds(that);
                        });

                        fixUpIds(that);
                    });
                });
            }(django.jQuery));
        </script>
        """
        return mark_safe(output)
示例#59
0
 def get_boolean_display(self, obj):
     if obj.boolean:
         return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
     return mark_safe('<span class="label label-warning"><i class="icon-thumbs-down"></i> NO</span>')