def format_value(value):
    if getattr(value, 'is_hyperlink', False):
        return mark_safe('<a href=%s>%s</a>' % (value, escape(value.name)))
    if value is None or isinstance(value, bool):
        return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
    elif isinstance(value, list):
        if any([isinstance(item, (list, dict)) for item in value]):
            template = loader.get_template('rest_framework/admin/list_value.html')
        else:
            template = loader.get_template('rest_framework/admin/simple_list_value.html')
        context = {'value': value}
        return template_render(template, context)
    elif isinstance(value, dict):
        template = loader.get_template('rest_framework/admin/dict_value.html')
        context = {'value': value}
        return template_render(template, context)
    elif isinstance(value, six.string_types):
        if (
            (value.startswith('http:') or value.startswith('https:')) and not
            re.search(r'\s', value)
        ):
            return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value)))
        elif '@' in value and not re.search(r'\s', value):
            return mark_safe('<a href="mailto:{value}">{value}</a>'.format(value=escape(value)))
        elif '\n' in value:
            return mark_safe('<pre>%s</pre>' % escape(value))
    return six.text_type(value)
예제 #2
0
def format_value(value):
    if getattr(value, 'is_hyperlink', False):
        return mark_safe('<a href=%s>%s</a>' % (value, escape(value.name)))
    if value is None or isinstance(value, bool):
        return mark_safe('<code>%s</code>' % {
            True: 'true',
            False: 'false',
            None: 'null'
        }[value])
    elif isinstance(value, list):
        if any([isinstance(item, (list, dict)) for item in value]):
            template = loader.get_template(
                'rest_framework/admin/list_value.html')
        else:
            template = loader.get_template(
                'rest_framework/admin/simple_list_value.html')
        context = {'value': value}
        return template_render(template, context)
    elif isinstance(value, dict):
        template = loader.get_template('rest_framework/admin/dict_value.html')
        context = {'value': value}
        return template_render(template, context)
    elif isinstance(value, six.string_types):
        if ((value.startswith('http:') or value.startswith('https:'))
                and not re.search(r'\s', value)):
            return mark_safe(
                '<a href="{value}">{value}</a>'.format(value=escape(value)))
        elif '@' in value and not re.search(r'\s', value):
            return mark_safe('<a href="mailto:{value}">{value}</a>'.format(
                value=escape(value)))
        elif '\n' in value:
            return mark_safe('<pre>%s</pre>' % escape(value))
    return six.text_type(value)
예제 #3
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        view = renderer_context['view']
        request = renderer_context['request']
        response = renderer_context['response']

        if not getattr(request, 'current_page', None):
            msg = "APIView class '{}' with 'renderer_class=(CMSPageRenderer, ...)' can only be used by a CMSApp"
            response = view.handle_exception(APIException(detail=msg.format(view.__class__)))

        if response.exception:
            template = self.get_exception_template(response)
            template_context = Context(self.get_template_context(data, renderer_context))
            return template.render(template_context)

        # set edit_mode, so that otherwise invisible placeholders can be edited inline
        edit_mode = getattr(request.current_page, 'publisher_is_draft', False)

        template_names = [request.current_page.get_template()]
        template = self.resolve_template(template_names)
        template_context = self.get_template_context(data, renderer_context)
        template_context.update(
            renderer_context,
            paginator=view.paginator,
            edit_mode=edit_mode,
        )
        return template_render(template, template_context, request=request)
예제 #4
0
 def to_html(self, request, queryset, view):
     context = {
         'lon': request.query_params.get('lon', ''),
         'lat': request.query_params.get('lat', '')
     }
     template = loader.get_template(self.template)
     return template_render(template, context)
예제 #5
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        view = renderer_context['view']
        request = renderer_context['request']
        response = renderer_context['response']

        if not getattr(request, 'current_page', None):
            msg = "APIView class '{}' with 'renderer_class=(CMSPageRenderer, ...)' can only be used by a CMSApp"
            response = view.handle_exception(
                APIException(detail=msg.format(view.__class__)))

        if response.exception:
            template = self.get_exception_template(response)
            template_context = Context(
                self.get_template_context(data, renderer_context))
            return template.render(template_context)

        # set edit_mode, so that otherwise invisible placeholders can be edited inline
        edit_mode = getattr(request.current_page, 'publisher_is_draft', False)

        template_names = [request.current_page.get_template()]
        template = self.resolve_template(template_names)
        template_context = self.get_template_context(data, renderer_context)
        template_context.update(
            renderer_context,
            paginator=view.paginator,
            edit_mode=edit_mode,
        )
        return template_render(template, template_context, request=request)
예제 #6
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders data to HTML, using Django's standard template rendering.

        The template name is determined by (in order of preference):

        1. An explicit .template_name set on the response.
        2. An explicit .template_name set on this class.
        3. The return result of calling view.get_template_names().
        """
        renderer_context = renderer_context or {}
        view = renderer_context['view']
        request = renderer_context['request']
        response = renderer_context['response']

        if response.exception:
            template = self.get_exception_template(response)
        else:
            template_names = self.get_template_names(response, view)
            template = self.resolve_template(template_names)

        if hasattr(self, 'resolve_context'):
            # Fallback for older versions.
            context = self.resolve_context(data, request, response)
        else:
            context = self.get_template_context(data, renderer_context)
        return template_render(template, context, request=request)
예제 #7
0
    def render_field(self, field, parent_style):
        if isinstance(field._field, serializers.HiddenField):
            return ''

        style = dict(self.default_style[field])
        style.update(field.style)
        if 'template_pack' not in style:
            style['template_pack'] = parent_style.get('template_pack',
                                                      self.template_pack)
        style['renderer'] = self

        # Get a clone of the field with text-only value representation.
        field = field.as_form_field()

        if style.get('input_type') == 'datetime-local' and isinstance(
                field.value, six.text_type):
            field.value = field.value.rstrip('Z')

        if 'template' in style:
            template_name = style['template']
        else:
            template_name = style['template_pack'].strip(
                '/') + '/' + style['base_template']

        template = loader.get_template(template_name)
        context = {'field': field, 'style': style}
        return template_render(template, context)
예제 #8
0
    def render_field(self, field, parent_style):
        if isinstance(field._field, serializers.HiddenField):
            return ''

        style = dict(self.default_style[field])
        style.update(field.style)
        if 'template_pack' not in style:
            style['template_pack'] = parent_style.get('template_pack', self.template_pack)
        style['renderer'] = self

        # If we are rendering a JSON Field we want to convert Python literals to Javascript literals
        if issubclass(field._proxy_class, JSONField):
            field.value = json.dumps(field.value)

        # Get a clone of the field with text-only value representation.
        field = field.as_form_field()


        if style.get('input_type') == 'datetime-local' and isinstance(field.value, six.text_type):
            field.value = field.value.rstrip('Z')

        if 'template' in style:
            template_name = style['template']
        else:
            template_name = style['template_pack'].strip('/') + '/' + style['base_template']

        template = loader.get_template(template_name)
        context = {'field': field, 'style': style}
        return template_render(template, context)
예제 #9
0
    def get_filter_form(self, data, view, request):
        if not hasattr(view, 'get_queryset') or not hasattr(
                view, 'filter_backends'):
            return

        # Infer if this is a list view or not.
        paginator = getattr(view, 'paginator', None)
        if isinstance(data, list):
            pass
        elif paginator is not None and data is not None:
            try:
                paginator.get_results(data)
            except (TypeError, KeyError):
                return
        elif not isinstance(data, list):
            return

        queryset = view.get_queryset()
        elements = []
        for backend in view.filter_backends:
            if hasattr(backend, 'to_html'):
                html = backend().to_html(request, queryset, view)
                if html:
                    elements.append(html)

        if not elements:
            return

        template = loader.get_template(self.filter_template)
        context = {'elements': elements}
        return template_render(template, context)
예제 #10
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders data to HTML, using Django's standard template rendering.

        The template name is determined by (in order of preference):

        1. An explicit .template_name set on the response.
        2. An explicit .template_name set on this class.
        3. The return result of calling view.get_template_names().
        """
        renderer_context = renderer_context or {}
        view = renderer_context['view']
        request = renderer_context['request']
        response = renderer_context['response']

        if response.exception:
            template = self.get_exception_template(response)
        else:
            template_names = self.get_template_names(response, view)
            template = self.resolve_template(template_names)

        if hasattr(self, 'resolve_context'):
            # Fallback for older versions.
            context = self.resolve_context(data, request, response)
        else:
            context = self.get_template_context(data, renderer_context)
        return template_render(template, context, request=request)
예제 #11
0
    def get_filter_form(self, data, view, request):
        if not hasattr(view, 'get_queryset') or not hasattr(view, 'filter_backends'):
            return

        # Infer if this is a list view or not.
        paginator = getattr(view, 'paginator', None)
        if isinstance(data, list):
            pass
        elif (paginator is not None and data is not None):
            try:
                paginator.get_results(data)
            except (TypeError, KeyError):
                return
        elif not isinstance(data, list):
            return

        queryset = view.get_queryset()
        elements = []
        for backend in view.filter_backends:
            if hasattr(backend, 'to_html'):
                html = backend().to_html(request, queryset, view)
                if html:
                    elements.append(html)

        if not elements:
            return

        template = loader.get_template(self.filter_template)
        context = {'elements': elements}
        return template_render(template, context)
예제 #12
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        codec = coreapi.codecs.CoreJSONCodec()
        schema = base64.b64encode(codec.encode(data))

        template = loader.get_template(self.template)
        context = {'schema': mark_safe(schema)}
        request = renderer_context['request']
        return template_render(template, context, request=request)
예제 #13
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        codec = coreapi.codecs.CoreJSONCodec()
        schema = base64.b64encode(codec.encode(data))

        template = loader.get_template(self.template)
        context = {'schema': mark_safe(schema)}
        request = renderer_context['request']
        return template_render(template, context, request=request)
예제 #14
0
 def to_html(self, request, queryset, view):
     filter_class = self.get_filter_class(view, queryset)
     if not filter_class:
         return None
     filter_instance = filter_class(request.query_params, queryset=queryset)
     context = {'filter': filter_instance}
     template = loader.get_template(self.template)
     return template_render(template, context)
예제 #15
0
파일: filters.py 프로젝트: HWHU/AlexaCare
    def to_html(self, request, queryset, view):
        if not getattr(view, 'search_fields', None):
            return ''

        term = self.get_search_terms(request)
        term = term[0] if term else ''
        context = {'param': self.search_param, 'term': term}
        template = loader.get_template(self.template)
        return template_render(template, context)
예제 #16
0
    def to_html(self, request, queryset, view):
        if not getattr(view, "search_fields", None):
            return ""

        term = self.get_search_terms(request)
        term = term[0] if term else ""
        context = {"param": self.search_param, "term": term}
        template = loader.get_template(self.template)
        return template_render(template, context)
예제 #17
0
 def to_html(self, request, queryset, view):
     filter_class = self.get_filter_class(view, queryset)
     if not filter_class:
         return None
     filter_instance = filter_class(request.query_params, queryset=queryset)
     context = {
         'filter': filter_instance
     }
     template = loader.get_template(self.template)
     return template_render(template, context)
예제 #18
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        response = renderer_context['response']

        if response and response.exception:
            request = renderer_context['request']
            template = self.get_exception_template(response)
            context = self.resolve_context(data, request, response)
            return template_render(template, context, request=request)

        return data
예제 #19
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        response = renderer_context['response']

        if response and response.exception:
            request = renderer_context['request']
            template = self.get_exception_template(response)
            context = self.resolve_context(data, request, response)
            return template_render(template, context, request=request)

        return data
예제 #20
0
    def to_html(self, request, queryset, view):
        if not getattr(view, 'search_fields', None):
            return ''

        term = self.get_search_terms(request)
        term = term[0] if term else ''
        context = {
            'param': self.search_param,
            'term': term
        }
        template = loader.get_template(self.template)
        return template_render(template, context)
예제 #21
0
    def to_html(self, request, queryset, view):
        filter_class = self.get_filter_class(view, queryset)
        if not filter_class:
            return None
        filter_instance = filter_class(request.query_params, queryset=queryset, request=request)

        try:
            template = loader.get_template(self.template)
        except TemplateDoesNotExist:
            template = Template(template_default)

        return template_render(template, context={"filter": filter_instance})
예제 #22
0
    def to_html(self, request, queryset, view):
        filter_class = self.get_filter_class(view, queryset)
        if not filter_class:
            return None
        filter_instance = filter_class(request.query_params, queryset=queryset)

        try:
            template = loader.get_template(self.template)
        except TemplateDoesNotExist:
            template = Template(template_default)

        return template_render(template, context={'filter': filter_instance})
예제 #23
0
    def to_html(self, request, queryset, view):
        filter_class = self.get_filter_class(view, queryset)
        if not filter_class:
            return None
        filter_instance = filter_class(request.query_params, queryset=queryset)

        # forces `form` evaluation before `qs` is called. This prevents an empty form from being cached.
        filter_instance.form

        context = {
            'filter': filter_instance
        }
        template = loader.get_template(self.template)
        return compat.template_render(template, context)
    def to_html(self, request, queryset, view):
        filter_class = self.get_filter_class(view, queryset)
        if not filter_class:
            return None
        filter_instance = filter_class(request.query_params, queryset=queryset)

        # forces `form` evaluation before `qs` is called. This prevents an empty form from being cached.
        filter_instance.form

        context = {
            'filter': filter_instance
        }
        template = loader.get_template(self.template)
        return template_render(template, context)
예제 #25
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render serializer data and return an HTML form, as a string.
        """
        form = data.serializer

        style = renderer_context.get('style', {})
        if 'template_pack' not in style:
            style['template_pack'] = self.template_pack
        style['renderer'] = self

        template_pack = style['template_pack'].strip('/')
        template_name = template_pack + '/' + self.base_template
        template = loader.get_template(template_name)
        context = {'form': form, 'style': style}
        return template_render(template, context)
    def to_html(self, request, queryset, view):
        filter_class = self.get_filter_class(view, queryset)
        if not filter_class:
            return None
        filter_instance = filter_class(request.query_params, queryset=queryset)

        # forces `form` evaluation before `qs` is called. This prevents an empty form from being cached.
        filter_instance.form

        try:
            template = loader.get_template(self.template)
        except TemplateDoesNotExist:
            template = Template(backends.template_default)

        return compat.template_render(template, context={
            'filter': filter_instance
        })
예제 #27
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        self.accepted_media_type = accepted_media_type or ''
        self.renderer_context = renderer_context or {}

        response = renderer_context['response']
        request = renderer_context['request']
        view = self.renderer_context['view']

        if response.status_code == status.HTTP_400_BAD_REQUEST:
            # Errors still need to display the list or detail information.
            # The only way we can get at that is to simulate a GET request.
            self.error_form = self.get_rendered_html_form(
                data, view, request.method, request)
            self.error_title = {
                'POST': 'Create',
                'PUT': 'Edit'
            }.get(request.method, 'Errors')

            with override_method(view, request, 'GET') as request:
                response = view.get(request, *view.args, **view.kwargs)
            data = response.data

        template = loader.get_template(self.template)
        context = self.get_context(data, accepted_media_type, renderer_context)
        ret = template_render(template,
                              context,
                              request=renderer_context['request'])

        # Creation and deletion should use redirects in the admin style.
        if (response.status_code == status.HTTP_201_CREATED) and ('Location'
                                                                  in response):
            response.status_code = status.HTTP_303_SEE_OTHER
            response['Location'] = request.build_absolute_uri()
            ret = ''

        if response.status_code == status.HTTP_204_NO_CONTENT:
            response.status_code = status.HTTP_303_SEE_OTHER
            try:
                # Attempt to get the parent breadcrumb URL.
                response['Location'] = self.get_breadcrumbs(request)[-2][1]
            except KeyError:
                # Otherwise reload current URL to get a 'Not Found' page.
                response['Location'] = request.full_path
            ret = ''

        return ret
예제 #28
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render the HTML for the browsable API representation.
        """
        self.accepted_media_type = accepted_media_type or ''
        self.renderer_context = renderer_context or {}

        template = loader.get_template(self.template)
        context = self.get_context(data, accepted_media_type, renderer_context)
        ret = template_render(template, context, request=renderer_context['request'])

        # Munge DELETE Response code to allow us to return content
        # (Do this *after* we've rendered the template so that we include
        # the normal deletion response code in the output)
        response = renderer_context['response']
        if response.status_code == status.HTTP_204_NO_CONTENT:
            response.status_code = status.HTTP_200_OK

        return ret
예제 #29
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render serializer data and return an HTML form, as a string.
        """
        form = data.serializer

        style = renderer_context.get('style', {})
        if 'template_pack' not in style:
            style['template_pack'] = self.template_pack
        style['renderer'] = self

        template_pack = style['template_pack'].strip('/')
        template_name = template_pack + '/' + self.base_template
        template = loader.get_template(template_name)
        context = {
            'form': form,
            'style': style
        }
        return template_render(template, context)
예제 #30
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render the HTML for the browsable API representation.
        """
        self.accepted_media_type = accepted_media_type or ''
        self.renderer_context = renderer_context or {}

        template = loader.get_template(self.template)
        context = self.get_context(data, accepted_media_type, renderer_context)
        ret = template_render(template, context, request=renderer_context['request'])

        # Munge DELETE Response code to allow us to return content
        # (Do this *after* we've rendered the template so that we include
        # the normal deletion response code in the output)
        response = renderer_context['response']
        if response.status_code == status.HTTP_204_NO_CONTENT:
            response.status_code = status.HTTP_200_OK

        return ret
예제 #31
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        view = renderer_context['view']
        request = renderer_context['request']
        response = renderer_context['response']
        template_context = self.get_template_context(dict(data),
                                                     renderer_context)

        if response.exception:
            template = self.get_exception_template(response)
        else:
            template_names = self.get_template_names(response, view)
            template = self.resolve_template(template_names)
            template_context['paginator'] = view.paginator
            # set edit_mode, so that otherwise invisible placeholders can be edited inline
            template_context[
                'edit_mode'] = request.current_page.publisher_is_draft

        template_context['data'] = data
        template_context.update(renderer_context)
        return template_render(template, template_context, request=request)
예제 #32
0
    def render(self, data, accepted_media_type=None, renderer_context=None):
        self.accepted_media_type = accepted_media_type or ''
        self.renderer_context = renderer_context or {}

        response = renderer_context['response']
        request = renderer_context['request']
        view = self.renderer_context['view']

        if response.status_code == status.HTTP_400_BAD_REQUEST:
            # Errors still need to display the list or detail information.
            # The only way we can get at that is to simulate a GET request.
            self.error_form = self.get_rendered_html_form(data, view, request.method, request)
            self.error_title = {'POST': 'Create', 'PUT': 'Edit'}.get(request.method, 'Errors')

            with override_method(view, request, 'GET') as request:
                response = view.get(request, *view.args, **view.kwargs)
            data = response.data

        template = loader.get_template(self.template)
        context = self.get_context(data, accepted_media_type, renderer_context)
        ret = template_render(template, context, request=renderer_context['request'])

        # Creation and deletion should use redirects in the admin style.
        if (response.status_code == status.HTTP_201_CREATED) and ('Location' in response):
            response.status_code = status.HTTP_302_FOUND
            response['Location'] = request.build_absolute_uri()
            ret = ''

        if response.status_code == status.HTTP_204_NO_CONTENT:
            response.status_code = status.HTTP_302_FOUND
            try:
                # Attempt to get the parent breadcrumb URL.
                response['Location'] = self.get_breadcrumbs(request)[-2][1]
            except KeyError:
                # Otherwise reload current URL to get a 'Not Found' page.
                response['Location'] = request.full_path
            ret = ''

        return ret
예제 #33
0
 def to_html(self, request, queryset, view):
     template = loader.get_template(self.template)
     context = self.get_template_context(request, queryset, view)
     return template_render(template, context)
예제 #34
0
 def render(self, data, accepted_media_type=None, renderer_context=None):
     template = loader.get_template(self.template)
     context = self.get_context(data, renderer_context['request'])
     return template_render(template, context, request=renderer_context['request'])
예제 #35
0
 def render(self, data, accepted_media_type=None, renderer_context=None):
     template = loader.get_template(self.template)
     context = self.get_context(data, renderer_context['request'])
     return template_render(template,
                            context,
                            request=renderer_context['request'])
예제 #36
0
 def to_html(self):
     template = loader.get_template(self.template)
     context = self.get_html_context()
     return template_render(template, context)
예제 #37
0
파일: filters.py 프로젝트: HWHU/AlexaCare
 def to_html(self, request, queryset, view):
     template = loader.get_template(self.template)
     context = self.get_template_context(request, queryset, view)
     return template_render(template, context)
예제 #38
0
 def to_html(self):
     template = loader.get_template(self.template)
     context = self.get_html_context()
     return template_render(template, context)