コード例 #1
0
 def __getattr__(self, field):
     value = getattr(self._wrapped, field)
     if field == 'logo':
         src = getattr(self._wrapped,
                       'logo_thumbnail')(False, self._logo_size,
                                         self._logo_crop)
         if src:
             try:
                 template_ = get_template("coop_cms/widgets/_img_logo.html")
                 value = template_.render(
                     make_context(
                         None, {
                             'url':
                             src.url,
                             'extra_classes':
                             get_text_from_template(
                                 "coop_cms/widgets/_imageedit_cssclass.html"
                             )
                         }))
             except TemplateDoesNotExist:
                 value = '<img class="logo" src="{0}" />'.format(src.url)
         else:
             value = ''
         return mark_safe(value)
     elif callable(value):
         try:
             return value()
         except KeyError:
             pass
     else:
         if isinstance(value, string_types):
             return mark_safe(value)
     return value
コード例 #2
0
 def render(self, context):
     """to html"""
     request = context.get('request', None)
     if not request.session.get('hide_accept_cookie_message', False):
         template_ = get_template(self.template_name)
         return template_.render(make_context(request, {}))
     else:
         return ""
コード例 #3
0
ファイル: coop_utils.py プロジェクト: ljean/coop_cms
 def render(self, context):
     """to html"""
     request = context.get('request', None)
     if not request.session.get('hide_accept_cookie_message', False):
         template_ = get_template(self.template_name)
         return template_.render(make_context(request, {}))
     else:
         return ""
コード例 #4
0
def view_navnode(request, tree):
    """show info about the node when selected"""
    try:
        response = {}

        node_id = request.POST['node_id']
        node = models.NavNode.objects.get(tree=tree, id=node_id)
        model_name = object_label = ""

        # get the admin url
        if node.content_type:
            app, mod = node.content_type.app_label, node.content_type.model
            admin_url = reverse("admin:{0}_{1}_change".format(app, mod),
                                args=(node.object_id, ))

            # load and render template for the object
            # try to load the corresponding template and if not found use the default one
            model_name = "{0}".format(node.content_type)
            object_label = "{0}".format(node.content_object)
            template = select_template([
                "coop_cms/navtree_content/{0}.html".format(
                    node.content_type.name),
                "coop_cms/navtree_content/default.html"
            ])
        else:
            admin_url = ""
            template = select_template(
                ["coop_cms/navtree_content/default.html"])

        context_dict = {
            "node": node,
            "admin_url": admin_url,
            "model_name": model_name,
            "object_label": object_label,
        }

        html = template.render(make_context(request, context_dict))

        # return data has dictionary
        response['html'] = html
        response['message'] = "Node content loaded."

        return response
    except Exception:
        logger.exception("view_navnode")
        raise
コード例 #5
0
ファイル: navigation.py プロジェクト: ljean/coop_cms
def view_navnode(request, tree):
    """show info about the node when selected"""
    try:
        response = {}

        node_id = request.POST['node_id']
        node = models.NavNode.objects.get(tree=tree, id=node_id)
        model_name = object_label = ""

        # get the admin url
        if node.content_type:
            app, mod = node.content_type.app_label, node.content_type.model
            admin_url = reverse("admin:{0}_{1}_change".format(app, mod), args=(node.object_id,))

            # load and render template for the object
            # try to load the corresponding template and if not found use the default one
            model_name = "{0}".format(node.content_type)
            object_label = "{0}".format(node.content_object)
            template = select_template([
                "coop_cms/navtree_content/{0}.html".format(node.content_type.name),
                "coop_cms/navtree_content/default.html"
            ])
        else:
            admin_url = ""
            template = select_template(["coop_cms/navtree_content/default.html"])

        context_dict = {
            "node": node,
            "admin_url": admin_url,
            "model_name": model_name,
            "object_label": object_label,
        }

        html = template.render(
            make_context(request, context_dict)
        )

        # return data has dictionary
        response['html'] = html
        response['message'] = "Node content loaded."

        return response
    except Exception:
        logger.exception("view_navnode")
        raise
コード例 #6
0
ファイル: webutils.py プロジェクト: BenjaminCherpas/coop_cms
def csrf_failure(request, reason=""):
    """
    Custom view used when request fails CSRF protection.

    ENABLED by default by coop_cms unless you set COOP_CMS_DO_NOT_INSTALL_CSRF_FAILURE_VIEW=True in settings.py
    """

    warn_text = "csrf_failure, reason: {0}".format(reason)
    logger.warn(warn_text)

    template = get_template('coop_cms/csrf_403.html')

    context = {
        'DEBUG': settings.DEBUG,
        'cookie_disabled': reason == REASON_NO_CSRF_COOKIE,
        'no_referer': reason == REASON_NO_REFERER,
    }

    html = template.render(make_context(request, context))

    return HttpResponseForbidden(html, content_type='text/html')
コード例 #7
0
 def _object_render(self, idx, obj, context):
     """convert object to html"""
     value = getattr(obj, self._field_name)
     template_name = self.kwargs.get('template_name', '')
     if template_name:
         template_name = self._resolve_arg(template_name, context)
         template_ = get_template(template_name)
         objects_count = self.get_objects_to_render_count()
         object_content = template_.render(
             make_context(
                 None,
                 {
                     'css_class':
                     obj.css_class,
                     'name':
                     obj.name,
                     'slug':
                     slugify(obj.name),
                     'id':
                     obj.id,
                     'index':
                     idx,
                     'objects_count':
                     objects_count,
                     'fragment':
                     self._render_value(
                         context, self._get_object_lookup(obj), value),
                     'form':
                     DummyEditableForm() if self._edit_mode else None,
                 },
             ))
     else:
         object_content = self._pre_object_render(obj)
         object_content += self._render_value(context,
                                              self._get_object_lookup(obj),
                                              value)
         object_content += self._post_object_render(obj)
     return object_content
コード例 #8
0
def show_media(request, media_type):
    """show media library"""
    try:
        if not request.user.is_staff:
            raise PermissionDenied

        try:
            page = int(request.GET.get('page', 0) or 0)
        except ValueError:
            page = 1
        is_ajax = page > 0
        media_filter = request.GET.get('media_filter', 0)
        skip_media_filter = False

        if request.session.get("coop_cms_media_doc", False):
            # force the doc
            media_type = 'document'
            del request.session["coop_cms_media_doc"]

        if media_type == 'image':
            queryset = models.Image.objects.all().order_by("ordering", "-created")
            context = {
                'media_url': reverse('coop_cms_media_images'),
                'media_slide_template': 'coop_cms/medialib/slide_images_content.html',
            }

        elif media_type == 'photologue':
            queryset, context = _get_photologue_media(request)
            skip_media_filter = True

        else:
            media_type = "document"
            queryset = models.Document.objects.all().order_by("ordering", "-created")
            context = {
                'media_url': reverse('coop_cms_media_documents'),
                'media_slide_template': 'coop_cms/medialib/slide_docs_content.html',
            }

        context['is_ajax'] = is_ajax
        context['media_type'] = media_type

        if not skip_media_filter:
            # list of lists of media_filters
            media_filters = [media.filters.all() for media in queryset.all()]
            # flat list of media_filters
            media_filters = itertools.chain(*media_filters)
            # flat list of unique media filters sorted by alphabetical order (ignore case)
            context['media_filters'] = sorted(
                list(set(media_filters)), key=lambda mf: mf.name.upper()
            )

            if int(media_filter):
                queryset = queryset.filter(filters__id=media_filter)
                context['media_filter'] = int(media_filter)

        page_obj = paginate(request, queryset, 12)

        context[media_type+'s'] = list(page_obj)
        context['page_obj'] = page_obj

        context["allow_photologue"] = "photologue" in settings.INSTALLED_APPS

        if int(media_filter):
            context["media_url"] += '?media_filter={0}'.format(media_filter)

        template = get_template('coop_cms/medialib/slide_base.html')
        html = template.render(make_context(request, context))

        if is_ajax:
            data = {
                'html': html,
                'media_type': media_type,
                'media_url': context["media_url"],
            }
            return HttpResponse(json.dumps(data), content_type="application/json")
        else:
            return HttpResponse(html)
    except Exception:
        logger.exception("show_media")
        raise
コード例 #9
0
ファイル: medialib.py プロジェクト: ljean/coop_cms
def show_media(request, media_type):
    """show media library"""
    try:
        if not request.user.is_staff:
            raise PermissionDenied

        try:
            page = int(request.GET.get('page', 0) or 0)
        except ValueError:
            page = 1
        is_ajax = page > 0
        media_filter = request.GET.get('media_filter', 0)
        skip_media_filter = False

        if request.session.get("coop_cms_media_doc", False):
            # force the doc
            media_type = 'document'
            del request.session["coop_cms_media_doc"]

        if media_type == 'image':
            queryset = models.Image.objects.all().order_by("ordering", "-created")
            context = {
                'media_url': reverse('coop_cms_media_images'),
                'media_slide_template': 'coop_cms/medialib/slide_images_content.html',
            }

        elif media_type == 'photologue':
            queryset, context = _get_photologue_media(request)
            skip_media_filter = True

        else:
            media_type = "document"
            queryset = models.Document.objects.all().order_by("ordering", "-created")
            context = {
                'media_url': reverse('coop_cms_media_documents'),
                'media_slide_template': 'coop_cms/medialib/slide_docs_content.html',
            }

        context['is_ajax'] = is_ajax
        context['media_type'] = media_type

        if not skip_media_filter:
            # list of lists of media_filters
            media_filters = [media.filters.all() for media in queryset.all()]
            # flat list of media_filters
            media_filters = itertools.chain(*media_filters)
            # flat list of unique media filters sorted by alphabetical order (ignore case)
            context['media_filters'] = sorted(
                list(set(media_filters)), key=lambda mf: mf.name.upper()
            )

            if int(media_filter):
                queryset = queryset.filter(filters__id=media_filter)
                context['media_filter'] = int(media_filter)

        page_obj = paginate(request, queryset, 12)

        context[media_type+'s'] = list(page_obj)
        context['page_obj'] = page_obj

        context["allow_photologue"] = "photologue" in settings.INSTALLED_APPS

        if int(media_filter):
            context["media_url"] += '?media_filter={0}'.format(media_filter)

        template = get_template('coop_cms/medialib/slide_base.html')
        html = template.render(make_context(request, context))

        if is_ajax:
            data = {
                'html': html,
                'media_type': media_type,
                'media_url': context["media_url"],
            }
            return HttpResponse(json.dumps(data), content_type="application/json")
        else:
            return HttpResponse(html)
    except Exception:
        logger.exception("show_media")
        raise
コード例 #10
0
    def _render_nodes(self, context, inner_context, safe_context):
        """Replace nested nodes with proper content"""
        managed_node_types = [
            TextNode,
            template.defaulttags.IfNode,
            IfCmsEditionNode,
            IfNotCmsEditionNode,
            template.defaulttags.ForNode,
        ]

        nodes_content = ""
        for node in self.nodelist_content:

            if any([
                    isinstance(node, node_type)
                    for node_type in managed_node_types
            ]):
                local_context = Context(safe_context)
                if hasattr(context, 'template'):
                    local_context.template = context.template
                content = node.render(local_context)

            elif node.__class__.__name__ == 'MediaListNode':
                content = node.render(context)
                safe_context[node.var_name] = context.get(node.var_name)
                inner_context[node.var_name] = context.get(node.var_name)

            elif node.__class__.__name__ == 'AssignmentNode':
                content = node.render(context)
                safe_context[node.target_var] = context.get(node.target_var)
                inner_context[node.target_var] = context.get(node.target_var)

            elif isinstance(node, IncludeNode):
                # monkey patching for django 1.8

                if isinstance(node.template, FilterExpression):
                    template_name = node.template.resolve(context)
                    node.template = get_template(template_name)
                context_dict = inner_context.copy()
                if node.extra_context:
                    for filter_expression in node.extra_context:
                        value = node.extra_context[filter_expression].resolve(
                            context)
                        context_dict[filter_expression] = value

                the_context = make_context(None, context_dict)
                content = node.template.render(the_context)

            elif isinstance(node, template.loader_tags.BlockNode):
                safe_context_var = Context(safe_context)
                safe_context_var.render_context[
                    'block_context'] = context.render_context.get(
                        'block_context', None)
                safe_context_var.template = getattr(
                    node, 'template', None) or template.Template("")
                #safe_context_var.template.engine = DummyEngine()
                content = node.render(safe_context_var)

            elif isinstance(node, VariableNode):
                if node.filter_expression.filters:
                    content = node.render(Context(context))
                else:
                    the_context = Context(safe_context)
                    the_context.template = getattr(
                        node, 'template', None) or template.Template("")
                    #the_context.template.engine = DummyEngine()
                    content = node.render(the_context)
            else:
                # monkey patching for django 1.8+
                the_context = Context(inner_context)
                the_context.template = getattr(node, 'template',
                                               None) or template.Template("")
                #the_context.template.engine = DummyEngine()
                content = node.render(the_context)

            nodes_content += content
        return nodes_content