Exemplo n.º 1
0
def prepare_password_changed_mail(user):
    """Return an e-mail notifying the user that their password changed.

    Args:
        user (django.contrib.auth.models.User):
            The user whose password changed.

    Returns:
        EmailMessage:
        The generated message.
    """
    server_url = get_server_url()

    context = {
        'api_token_url': AuthenticationPage.get_absolute_url(),
        'has_api_tokens': user.webapi_tokens.exists(),
        'server_url': server_url,
        'user': user,
    }

    user_email = build_email_address_for_user(user)
    text_body = render_to_string(
        template_name='notifications/password_changed.txt', context=context)
    html_body = render_to_string(
        template_name='notifications/password_changed.html', context=context)

    return EmailMessage(subject='Password changed for user "%s" on %s' %
                        (user.username, server_url),
                        text_body=text_body,
                        html_body=html_body,
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        sender=settings.DEFAULT_FROM_EMAIL,
                        to=(user_email, ))
Exemplo n.º 2
0
def prepare_webapi_token_mail(webapi_token, op):
    """Return an e-mail message notifying a user about a WebAPI token change.

    Args:
        webapi_token (reviewboard.notifications.models.WebAPIToken):
            The token that was created, updated, or deleted.

        op (unicode):
            The operation on the token. This is one of:

            * ``'created'``
            * ``'updated'``
            * ``'deleted'``

    Returns:
        EmailMessage:
        The genereated e-mail.
    """
    product_name = settings.PRODUCT_NAME

    if op == 'created':
        subject = 'New %s API token created' % product_name
        template_name = 'notifications/api_token_created'
    elif op == 'updated':
        subject = '%s API token updated' % product_name
        template_name = 'notifications/api_token_updated'
    elif op == 'deleted':
        subject = '%s API token deleted' % product_name
        template_name = 'notifications/api_token_deleted'
    else:
        raise ValueError('Unexpected op "%s" passed to mail_webapi_token.' %
                         op)

    user = webapi_token.user
    user_email = build_email_address_for_user(user)

    context = {
        'api_token': webapi_token,
        'api_tokens_url': AuthenticationPage.get_absolute_url(),
        'partial_token': '%s...' % webapi_token.token[:10],
        'user': user,
        'site_root_url': get_server_url(),
        'PRODUCT_NAME': product_name,
    }

    text_message = render_to_string(template_name='%s.txt' % template_name,
                                    context=context)
    html_message = render_to_string(template_name='%s.html' % template_name,
                                    context=context)

    return EmailMessage(subject=subject,
                        text_body=text_message,
                        html_body=html_message,
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        sender=settings.DEFAULT_FROM_EMAIL,
                        to=[user_email])
Exemplo n.º 3
0
    def render_value(self, value):
        """Render the field for the given value.

        Args:
            value (int):
                The diffset primary key.

        returns:
            django.utils.safestring.SafeText:
            The rendered value.
        """
        if not value:
            return ''

        commits = list(DiffCommit.objects.filter(diffset_id=value))
        submitter_name = self.review_request_details.submitter.get_full_name()

        include_author_name = not submitter_name
        to_expand = set()

        for commit in commits:
            if commit.author_name != submitter_name:
                include_author_name = True

            if commit.summary.strip() != commit.commit_message.strip():
                to_expand.add(commit.pk)

        return render_to_string(template_name='reviews/commit_list_field.html',
                                request=self.request,
                                context={
                                    'include_author_name': include_author_name,
                                    'commits': commits,
                                    'to_expand': to_expand,
                                })
Exemplo n.º 4
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The name of the widget.

            value (unicode):
                The value of the widget.

            attrs (dict):
                The attributes of the widget.

        Returns:
            django.utils.safestring.SafeText:
            The rendered widget.
        """
        field = super(CopyableTextInput, self).render(name, value, attrs)

        return render_to_string(
            self.template_name,
            {
                'field': field,
                'id': attrs['id'],
            })
    def render_value(self, value):
        """Render the field for the given value.

        Args:
            value (int):
                The diffset primary key.

        returns:
            django.utils.safestring.SafeText:
            The rendered value.
        """
        if not value:
            return ''

        commits = list(
            DiffCommit.objects
            .filter(diffset_id=value)
            .order_by('id')
        )
        context = self._get_common_context(commits)
        context['commits'] = commits

        return render_to_string(
            template_name='reviews/commit_list_field.html',
            request=self.request,
            context=context)
Exemplo n.º 6
0
    def render(self):
        """Render the item.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML for the item.
        """
        count = self.get_count()
        context = {
            'datagrid': self.datagrid,
            'label': self.label,
            'icon_name': self.icon_name or '',
            'view_id': self.view_id,
            'view_args': self.view_args,
            'count': count,
            'has_count': count is not None,
            'url': self.get_url(),
            'active': self.is_active(),
            'css_classes': self.css_classes or [],
        }
        context.update(self.get_extra_context())

        return render_to_string(template_name=self.template_name,
                                context=context,
                                request=self.datagrid.request)
Exemplo n.º 7
0
    def render(self, request, user, size, template_name=None):
        """Render a user's avatar to HTML.

        By default, this is rendered with the template specified by the
        :py:attr:`template_name` attribute. This behaviour can be overridden
        by subclasses.

        Args:
            request (django.http.HttpRequest):
                The HTTP request. This can be ``None`` if not available.

            user (django.contrib.auth.models.User):
                The user for whom the avatar is to be rendered.

            size (int):
                The requested avatar size (height and width) in pixels.

            template_name (unicode, optional):
                The name of the template to use for rendering.

        Returns:
            unicode: The rendered avatar HTML.
        """
        if template_name is None:
            template_name = self.template_name

        return render_to_string(template_name, {
            'request': request,
            'urls': self.get_avatar_urls(request, user, size),
            'user': user,
            'size': size,
        })
Exemplo n.º 8
0
    def render_change_entry_html(self, info):
        """Render the change entry HTML for this field.

        Args:
            info (dict):
                The change entry info for this field. See
                :py:meth:`record_change_entry` for the format.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML.
        """
        commits = self.data.commits_by_diffset_id

        old_commits = commits[info['old']]
        new_commits = commits[info['new']]

        context = self._get_common_context(chain(old_commits, new_commits))
        context.update({
            'old_commits': old_commits,
            'new_commits': new_commits,
        })

        return render_to_string(
            template_name='reviews/changedesc_commit_list.html',
            request=self.request,
            context=context)
Exemplo n.º 9
0
    def render_to_string(self, request, inline=True):
        """Render the Review UI to an HTML string.

        This renders the Review UI to a string for use in embedding into
        either an existing page or a new page.

        Args:
            request (django.http.HttpRequest):
                The HTTP request from the client.

            inline (bool, optional):
                Whether to render this such that it can be embedded into an
                existing page, instead of as a standalone page.

        Returns:
            django.utils.safestring.SafeText:
            The HTML for the Review UI.
        """
        self.request = request

        try:
            context = self.build_render_context(request, inline=inline)

            return render_to_string(template_name=self.template_name,
                                    context=context,
                                    request=request)
        except Exception as e:
            logger.exception('Error when rendering %r: %s', self, e)
            raise
Exemplo n.º 10
0
def include_as_string(context, template_name):
    """Include the contents of a template as an escaped string.

    This is primarily for use with JavaScript. It allows another template
    to be rendered (with the current context) and returned as an escaped
    string.

    Args:
        template_name (unicode):
            The name of the template to render.

    Returns:
        The escaped content from the template.

    Example:
        .. code-block:: html+django

           <script>
           var s = {% include_as_string "message.txt" %};
           </script>
    """
    s = render_to_string(template_name, context)
    s = s.replace("'", "\\'")
    s = s.replace("\n", "\\\n")

    # Since this works like {% include %}, we have to trust the resulting
    # content here. It's still possible that a nefarious template could cause
    # problems, but this is the responsibility of the caller.
    #
    # In prior versions of Django (< 1.9), this was implicitly marked safe.
    return mark_safe("'%s'" % s)
Exemplo n.º 11
0
def navigation_bar_hooks(context):
    """Displays all registered navigation bar entries."""
    html = []

    for hook in NavigationBarHook.hooks:
        try:
            for nav_info in hook.get_entries(context):
                if nav_info:
                    url_name = nav_info.get('url_name', None)

                    if url_name:
                        nav_info['url'] = local_site_reverse(
                            url_name, request=context.get('request'))

                    context.push()
                    context['entry'] = nav_info
                    html.append(render_to_string(
                        template_name='extensions/navbar_entry.html',
                        context=context))
                    context.pop()
        except Exception as e:
            extension = hook.extension
            logger.error('Error when running NavigationBarHook.'
                         'get_entries function in extension: "%s": %s',
                         extension.id, e, exc_info=1)

    return mark_safe(''.join(html))
Exemplo n.º 12
0
def action_hooks(context, hook_cls, action_key="action",
                 template_name="extensions/action.html"):
    """Displays all registered action hooks from the specified ActionHook."""
    html = []

    for hook in hook_cls.hooks:
        try:
            for actions in hook.get_actions(context):
                if actions:
                    context.push()
                    context[action_key] = actions

                    try:
                        html.append(render_to_string(
                            template_name=template_name,
                            context=context))
                    except Exception as e:
                        logger.error(
                            'Error when rendering template for action "%s" '
                            'for hook %r in extension "%s": %s',
                            action_key, hook, hook.extension.id, e,
                            exc_info=1)

                    context.pop()
        except Exception as e:
            logger.error('Error when running get_actions() on hook %r '
                         'in extension "%s": %s',
                         hook, hook.extension.id, e, exc_info=1)

    return mark_safe(''.join(html))
Exemplo n.º 13
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The name of the widget.

            value (unicode):
                The value of the widget.

            attrs (dict, optional):
                Additional attributes to pass to the widget.

        Returns:
            django.util.safestring.SafeText:
            The rendered widget.
        """
        attrs = self.build_attrs(attrs)

        return render_to_string(
            template_name='hostingsvcs/gitlab/url_widget.html',
            context={
                'attrs': attrs,
                'id': attrs.pop('id'),
                'is_custom': value and value != self.GITLAB,
                'name': name,
                'value': value or '',
            })
Exemplo n.º 14
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The name of the widget.

            value (unicode):
                The value of the widget.

            attrs (dict):
                The attributes of the widget.

        Returns:
            django.utils.safestring.SafeText:
            The rendered widget.
        """
        field = super(CopyableTextInput, self).render(name, value, attrs)

        return render_to_string(
            self.template_name,
            {
                'field': field,
                'id': attrs['id'],
            })
Exemplo n.º 15
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The base name used for the ``<input>`` elements. Specific
                names will be composed from this.

            value (unicode):
                The current value for the field.

            attrs (dict, optional):
                HTML attributes for the widget. This is used only to set an
                ``id`` attribute for the field.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML for the widget.
        """
        if attrs is None:
            attrs = {}

        return render_to_string('privacy/consent/consent_widget.html',
                                context={
                                    'ALLOW': ConsentRequirementField.ALLOW,
                                    'BLOCK': ConsentRequirementField.BLOCK,
                                    'consent_requirement':
                                    self.consent_requirement,
                                    'icons': self.consent_requirement.icons,
                                    'id': attrs.get('id', ''),
                                    'name': name,
                                    'value': value,
                                })
Exemplo n.º 16
0
    def render_change_entry_html(self, info):
        """Render the change entry HTML for this field.

        Args:
            info (dict):
                The change entry info for this field. See
                :py:meth:`record_change_entry` for the format.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML.
        """
        commits = self.data.commits_by_diffset_id

        old_commits = commits[info['old']]
        new_commits = commits[info['new']]

        submitter_name = self.review_request_details.submitter.get_full_name()
        include_author_name = any(
            commit.author_name != submitter_name
            for commit in chain(old_commits, new_commits))

        return render_to_string(
            template_name='reviews/changedesc_commit_list.html',
            request=self.request,
            context={
                'old_commits': old_commits,
                'new_commits': new_commits,
                'include_author_name': include_author_name,
            })
Exemplo n.º 17
0
def display_review_request_trophies(context, review_request):
    """Returns the HTML for the trophies awarded to a review request."""
    trophy_models = Trophy.objects.get_trophies(review_request)

    if not trophy_models:
        return ''

    trophies = []

    for trophy_model in trophy_models:
        trophy_type_cls = trophy_model.trophy_type

        if trophy_type_cls is not UnknownTrophy:
            try:
                trophy_type = trophy_type_cls()
                text = trophy_type.format_display_text(context['request'],
                                                       trophy_model)

                trophies.append({
                    'image_urls': trophy_type.image_urls,
                    'image_width': trophy_type.image_width,
                    'image_height': trophy_type.image_height,
                    'name': trophy_type.name,
                    'text': text,
                })
            except Exception as e:
                logger.error('Error when rendering trophy %r (%r): %s',
                             trophy_model.pk, trophy_type_cls, e,
                             exc_info=1)

    return render_to_string(
        template_name='reviews/trophy_box.html',
        context={
            'trophies': trophies,
        })
Exemplo n.º 18
0
    def render_change_entry_html(self, info):
        """Render the change entry HTML for this field.

        Args:
            info (dict):
                The change entry info for this field. See
                :py:meth:`record_change_entry` for the format.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML.
        """
        commits = self.data.commits_by_diffset_id

        old_commits = commits[info['old']]
        new_commits = commits[info['new']]

        context = self._get_common_context(chain(old_commits, new_commits))
        context.update({
            'old_commits': old_commits,
            'new_commits': new_commits,
        })

        return render_to_string(
            template_name='reviews/changedesc_commit_list.html',
            request=self.request,
            context=context)
Exemplo n.º 19
0
    def render(self,
               context,
               action_key='action',
               template_name='reviews/action.html'):
        """Render this action instance and return the content as HTML.

        Args:
            context (django.template.Context):
                The collection of key-value pairs that is passed to the
                template in order to render this action.

            action_key (unicode, optional):
                The key to be used for this action in the context map.

            template_name (unicode, optional):
                The name of the template to be used for rendering this action.

        Returns:
            unicode: The action rendered in HTML.
        """
        content = ''

        if self.should_render(context):
            context.push()

            try:
                context[action_key] = self.copy_to_dict(context)
                content = render_to_string(template_name, context)
            finally:
                context.pop()

        return content
Exemplo n.º 20
0
def expand_fragment_link(context,
                         expanding,
                         tooltip,
                         expand_above,
                         expand_below,
                         text=None):
    """Renders a diff comment fragment expansion link.

    This link will expand the context by the supplied `expanding_above` and
    `expanding_below` values.

    `expanding` is expected to be one of 'above', 'below', or 'line'."""

    lines_of_context = context['lines_of_context']

    image_class = 'rb-icon-diff-expand-%s' % expanding
    expand_pos = (lines_of_context[0] + expand_above,
                  lines_of_context[1] + expand_below)

    return render_to_string(template_name='reviews/expand_link.html',
                            context={
                                'tooltip': tooltip,
                                'text': text,
                                'comment_id': context['comment'].id,
                                'expand_pos': expand_pos,
                                'image_class': image_class,
                            })
Exemplo n.º 21
0
def include_as_string(context, template_name):
    """Include the contents of a template as an escaped string.

    This is primarily for use with JavaScript. It allows another template
    to be rendered (with the current context) and returned as an escaped
    string.

    Args:
        template_name (unicode):
            The name of the template to render.

    Returns:
        The escaped content from the template.

    Example:
        .. code-block:: html+django

           <script>
           var s = {% include_as_string "message.txt" %};
           </script>
    """
    s = render_to_string(template_name, context)
    s = s.replace("'", "\\'")
    s = s.replace("\n", "\\\n")

    # Since this works like {% include %}, we have to trust the resulting
    # content here. It's still possible that a nefarious template could cause
    # problems, but this is the responsibility of the caller.
    #
    # In prior versions of Django (< 1.9), this was implicitly marked safe.
    return mark_safe("'%s'" % s)
Exemplo n.º 22
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The name of the field.

            value (unicode):
                The value of the field.

            attrs (dict, optional):
                The widget's attributes.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML.
        """
        field = super(OAuthSecretInputWidget, self).render(name,
                                                           value,
                                                           attrs=attrs)

        return render_to_string(template_name=self.template_name,
                                context={
                                    'field': field,
                                    'id': attrs['id'],
                                    'name': name,
                                    'api_url': self.api_url,
                                })
Exemplo n.º 23
0
def manual_updates_required(request, updates):
    """Render a page showing required updates that the admin must make.

    Args:
        request (django.http.HttpRequest):
            The HTTP request from the client.

        updates (list):
            The list of required updates to display on the page.

    Returns:
        django.http.HttpResponse:
        The response to send to the client.
    """
    return render(
        request=request,
        template_name='admin/manual_updates_required.html',
        context={
            'updates': [
                render_to_string(template_name=update_template_name,
                                 context=extra_context,
                                 request=request)
                for update_template_name, extra_context in updates
            ],
        })
Exemplo n.º 24
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The base name used for the ``<input>`` elements. Specific
                names will be composed from this.

            value (unicode):
                The current value for the field.

            attrs (dict, optional):
                HTML attributes for the widget. This is used only to set an
                ``id`` attribute for the field.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML for the widget.
        """
        if attrs is None:
            attrs = {}

        return render_to_string(
            'privacy/consent/consent_widget.html',
            context={
                'ALLOW': ConsentRequirementField.ALLOW,
                'BLOCK': ConsentRequirementField.BLOCK,
                'consent_requirement': self.consent_requirement,
                'icons': self.consent_requirement.icons,
                'id': attrs.get('id', ''),
                'name': name,
                'value': value,
            })
Exemplo n.º 25
0
def errorbox(context, nodelist, box_id=None):
    """
    Displays an error box around content, with an optional ID.
    """
    return render_to_string('deco/errorbox.html', {
        'box_id': box_id or "",
        'content': nodelist.render(context)
    })
Exemplo n.º 26
0
def errorbox(context, nodelist, box_id=None):
    """
    Displays an error box around content, with an optional ID.
    """
    return render_to_string('deco/errorbox.html', {
        'box_id': box_id or "",
        'content': nodelist.render(context)
    })
Exemplo n.º 27
0
def box(context, nodelist, classname=None):
    """
    Displays a box container around content, with an optional class name.
    """
    return render_to_string('deco/box.html', {
        'classname': classname or "",
        'content': nodelist.render(context)
    })
Exemplo n.º 28
0
def box(context, nodelist, classname=None):
    """
    Displays a box container around content, with an optional class name.
    """
    return render_to_string('deco/box.html', {
        'classname': classname or "",
        'content': nodelist.render(context)
    })
Exemplo n.º 29
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The name of the field.

            value (list):
                The current value of the field.

            attrs (dict, optional):
                Attributes for the HTML element.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML.
        """
        if value:
            if not self.multivalued:
                value = [value]

            value = [v for v in value if v]
            input_value = ','.join(force_text(v) for v in value)
            existing_groups = (Group.objects.filter(
                pk__in=value).order_by('name'))
        else:
            input_value = None
            existing_groups = []

        final_attrs = dict(self.attrs, **attrs)
        final_attrs['name'] = name

        input_html = super(RelatedGroupWidget,
                           self).render(name, input_value, attrs)

        group_data = []

        for group in existing_groups:
            data = {
                'name': group.name,
                'display_name': group.display_name,
                'id': group.pk,
            }

            group_data.append(data)

        return render_to_string(
            template_name='admin/related_group_widget.html',
            context={
                'input_html': mark_safe(input_html),
                'input_id': final_attrs['id'],
                'local_site_name': self.local_site_name,
                'multivalued': self.multivalued,
                'groups': group_data,
                'invite_only': self.invite_only,
            })
Exemplo n.º 30
0
def exception_traceback_string(request, e, template_name, extra_context={}):
    context = {'error': e}
    context.update(extra_context)

    if not isinstance(e, UserVisibleError):
        context['trace'] = traceback.format_exc()

    return render_to_string(template_name=template_name,
                            context=context,
                            request=request)
Exemplo n.º 31
0
def render_star(user, obj):
    """
    Does the actual work of rendering the star. The star tag is a wrapper
    around this.
    """
    if user.is_anonymous():
        return ""

    profile = None

    if not hasattr(obj, 'starred'):
        try:
            profile = user.get_profile(create_if_missing=False)
        except Profile.DoesNotExist:
            return ''

    if isinstance(obj, ReviewRequest):
        obj_info = {
            'type': 'reviewrequests',
            'id': obj.display_id
        }

        if hasattr(obj, 'starred'):
            starred = obj.starred
        else:
            starred = \
                profile.starred_review_requests.filter(pk=obj.id).exists()
    elif isinstance(obj, Group):
        obj_info = {
            'type': 'groups',
            'id': obj.name
        }

        if hasattr(obj, 'starred'):
            starred = obj.starred
        else:
            starred = profile.starred_groups.filter(pk=obj.id).exists()
    else:
        raise template.TemplateSyntaxError(
            "star tag received an incompatible object type (%s)" %
            type(obj))

    if starred:
        image_alt = _("Starred")
    else:
        image_alt = _("Click to star")

    return render_to_string(
        template_name='reviews/star.html',
        context={
            'object': obj_info,
            'starred': int(starred),
            'alt': image_alt,
            'user': user,
        })
Exemplo n.º 32
0
    def as_html(self):
        """Return the field rendered to HTML.

        Returns:
            django.utils.safetext.SafeString:
            The rendered field.
        """
        return render_to_string(
            template_name='reviews/review_request_field.html',
            context={
                'field': self,
            })
Exemplo n.º 33
0
    def fetch_feed():
        import feedparser

        data = urlopen(url).read()

        parser = feedparser.parse(data)

        context = {
            'parser': parser,
        }
        context.update(extra_context)

        return render_to_string(template_name, context, request)
Exemplo n.º 34
0
    def fetch_feed():
        import feedparser

        data = urlopen(url).read()

        parser = feedparser.parse(data)

        context = {
            'parser': parser,
        }
        context.update(extra_context)

        return render_to_string(template_name, context, request)
Exemplo n.º 35
0
def prepare_user_registered_mail(user):
    """Prepare an e-mail to the administrators notifying of a new user.

    Args:
        user (django.contrib.auth.models.User):
            The user who registered.

    Returns:
        EmailMessage:
        The generated e-mail.
    """
    subject = 'New %s user registration for %s' % (settings.PRODUCT_NAME,
                                                   user.username)

    context = {
        'site_url':
        _get_server_base_url(),
        'user':
        user,
        'user_url':
        build_server_url(reverse('admin:auth_user_change', args=(user.id, ))),
    }

    text_message = render_to_string(
        template_name='notifications/new_user_email.txt', context=context)
    html_message = render_to_string(
        template_name='notifications/new_user_email.html', context=context)

    return EmailMessage(subject=subject.strip(),
                        text_body=text_message,
                        html_body=html_message,
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        sender=settings.DEFAULT_FROM_EMAIL,
                        to=[
                            build_email_address(full_name=admin[0],
                                                email=admin[1])
                            for admin in settings.ADMINS
                        ])
Exemplo n.º 36
0
    def render(self, request):
        """Render the widget to a string.

        Args:
            request (django.http.HttpRequest):
                The HTTP request from the client.

        Returns:
            django.utils.safestring.SafeText:
            The rendered widget HTML.
        """
        return render_to_string(template_name=self.template_name,
                                context=dict({
                                    'widget': self,
                                }, **self.get_extra_context(request)),
                                request=request)
Exemplo n.º 37
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The field name.

            value (unicode):
                The field value.

            attrs (dict, optional):
                Additional attributes.

        Returns:
            django.utils.safestring.SafeText:
            The rendered widget.
        """
        attrs = self.build_attrs(attrs)
        id_ = attrs.pop('id')

        if 'class' in attrs:
            attrs['class'] += ' list-edit-item'
        else:
            attrs['class'] = 'list-edit-item'

        value = value or ''
        value_list = list(
            filter(len, (item.strip() for item in value.split(self._sep))))

        return render_to_string(
            self.template_name, {
                'name':
                name,
                'value':
                value,
                'attrs':
                format_html_join('', ' {0}="{1}"', sorted(
                    six.iteritems(attrs))),
                'id':
                id_,
                'remove_text':
                _('Remove this item.'),
                'sep':
                self._sep,
                'value_list':
                value_list,
            })
Exemplo n.º 38
0
    def render(self, name, value, attrs=None):
        """Render the widget.

        Args:
            name (unicode):
                The field name.

            value (unicode):
                The field value.

            attrs (dict, optional):
                Additional attributes.

        Returns:
            django.utils.safestring.SafeText:
            The rendered widget.
        """
        attrs = self.build_attrs(attrs)
        id_ = attrs.pop('id')

        if 'class' in attrs:
            attrs['class'] += ' list-edit-item'
        else:
            attrs['class'] = 'list-edit-item'

        value = value or ''
        value_list = list(
            filter(len, (item.strip() for item in value.split(self._sep)))
        )

        return render_to_string(
            self.template_name,
            {
                'name': name,
                'value': value,
                'attrs': format_html_join('', ' {0}="{1}"',
                                          sorted(six.iteritems(attrs))),
                'id': id_,
                'remove_text': _('Remove this item.'),
                'sep': self._sep,
                'value_list': value_list,
            })
Exemplo n.º 39
0
    def render(self):
        """Render the page to a string.

        :py:attr:`template_name` will be used to render the page. The
        template will be passed ``page`` (this page's instance) and
        ``forms`` (the list of :py:class:`ConfigPageForm` instances to
        render).

        Subclasses can override this to provide additional rendering logic.

        Returns:
            unicode: The rendered page as HTML.
        """
        return render_to_string(
            template_name=self.template_name,
            context={
                'page': self,
                'forms': self.forms,
            },
            request=self.request)
Exemplo n.º 40
0
    def render(self):
        """Render the form to a string.

        :py:attr:`template_name` will be used to render the form. The
        template will be passed ``form`` (this form's instance) and
        ``page`` (the parent :py:class:`ConfigPage`).

        Subclasses can override this to provide additional rendering logic.

        Returns:
            unicode: The rendered form as HTML.
        """
        context = dict({
            'form': self,
            'page': self.page,
        }, **self.get_extra_context())

        return render_to_string(template_name=self.template_name,
                                context=context,
                                request=self.request)
Exemplo n.º 41
0
    def render_value(self, value):
        """Render the field for the given value.

        Args:
            value (int):
                The diffset primary key.

        returns:
            django.utils.safestring.SafeText:
            The rendered value.
        """
        if not value:
            return ''

        commits = list(DiffCommit.objects.filter(diffset_id=value))
        context = self._get_common_context(commits)
        context['commits'] = commits

        return render_to_string(
            template_name='reviews/commit_list_field.html',
            request=self.request,
            context=context)
Exemplo n.º 42
0
def render(request, template_name, context=None, content_type=None,
           status=None, using=None):
    """Render a template name to a response.

    This provides compatibility for the :py:func:`django.shortcuts.loader`
    across Django 1.6 on up.

    Args:
        request (django.http.HttpRequest):
            The HTTP request from the client.

        template_name (unicode):
            The name of the template to render.

        context (dict, optional):
            The template context.

        content_type (unicode, optional);
            An optional content type to set for the response.

        status (int, optional):
            An optional HTTP status code to set for the response.

        using (unicode, optional):
            The optional template render backend to use to render this
            template. This is ignored for Django 1.6.

    Returns:
        django.http.HttpResponse:
        The resulting HTTP response.
    """
    content = render_to_string(template_name=template_name,
                               context=context,
                               request=request,
                               using=using)

    return HttpResponse(content,
                        content_type=content_type,
                        status=status)
Exemplo n.º 43
0
    def render_to_string(self, request, context):
        """Renders the content for the hook.

        By default, this renders the provided template name to a string
        and returns it.
        """
        context_data = {
            'extension': self.extension,
        }
        context_data.update(self.get_extra_context(request, context))
        context_data.update(self.extra_context)

        # Note that context.update implies a push().
        context.update(context_data)

        s = render_to_string(template_name=self.template_name,
                             context=context,
                             request=request)

        context.pop()

        return s
Exemplo n.º 44
0
    def render(self, name, value, attrs=None):
        """Render the widget to HTML.

        This will serialize all the choices, operators, and existing
        conditions and render an HTML representation, along with setting up
        JavaScript support for configuring the conditions.

        Args:
            name (unicode):
                The base form field name of the widget.

            value (dict):
                The serialized condition set for the field.

            attrs (dict, optional):
                Additional HTML element attributes for the fields.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML for the widget.
        """
        return render_to_string(self.template_name,
                                self.get_context(name, value, attrs))
Exemplo n.º 45
0
def quoted_email(context, template_name):
    """
    Renders a specified template as a quoted reply, using the current context.
    """
    return quote_text(render_to_string(template_name, context))