Exemplo n.º 1
0
def update_logo(request, article_id):
    """update logo"""
    try:
        article = get_object_or_404(get_article_class(), id=article_id)
        if request.method == "POST":
            form = ArticleLogoForm(request.POST, request.FILES)
            if form.is_valid():
                article.temp_logo = form.cleaned_data['image']
                article.save()
                url = article.logo_thumbnail(True).url
                data = {'ok': True, 'src': url}
                return HttpResponse(json.dumps(data), content_type='application/json')
            else:
                template = get_template('coop_cms/popup_update_logo.html')
                html = template.render(locals())
                data = {'ok': False, 'html': html}
                return HttpResponse(json.dumps(data), content_type='application/json')
        else:
            form = ArticleLogoForm()

        return render(
            request,
            'coop_cms/popup_update_logo.html',
            locals()
        )
    except Exception:
        logger.exception("update_logo")
        raise
Exemplo n.º 2
0
def upload_doc(request):
    """upload document"""
    try:
        if not request.user.has_perm("coop_cms.add_document"):
            raise PermissionDenied()

        if request.method == "POST":
            form = AddDocForm(request.POST, request.FILES)
            if form.is_valid():
                doc = form.save()
                if not doc.name:
                    doc.name = os.path.splitext(os.path.basename(doc.file.name))[0]
                    doc.save()

                filters = form.cleaned_data['filters']
                if filters:
                    doc.filters.add(*filters)
                    doc.save()

                request.session["coop_cms_media_doc"] = True

                return HttpResponse("close_popup_and_media_slide")
        else:
            form = AddDocForm()

        return render(
            request,
            'coop_cms/popup_upload_doc.html',
            locals()
        )
    except Exception:
        logger.exception("upload_doc")
        raise
Exemplo n.º 3
0
def update_logo(request, article_id):
    """update logo"""
    try:
        article = get_object_or_404(get_article_class(), id=article_id)
        if request.method == "POST":
            form = ArticleLogoForm(request.POST, request.FILES)
            if form.is_valid():
                article.temp_logo = form.cleaned_data['image']
                article.save()
                url = article.logo_thumbnail(True).url
                data = {'ok': True, 'src': url}
                return HttpResponse(json.dumps(data), content_type='application/json')
            else:
                template = get_template('coop_cms/popup_update_logo.html')
                html = template.render(locals())
                data = {'ok': False, 'html': html}
                return HttpResponse(json.dumps(data), content_type='application/json')
        else:
            form = ArticleLogoForm()

        return render(
            request,
            'coop_cms/popup_update_logo.html',
            locals()
        )
    except Exception:
        logger.exception("update_logo")
        raise
Exemplo n.º 4
0
def upload_doc(request):
    """upload document"""
    try:
        if not request.user.has_perm("coop_cms.add_document"):
            raise PermissionDenied()

        if request.method == "POST":
            form = AddDocForm(request.POST, request.FILES)
            if form.is_valid():
                doc = form.save()
                if not doc.name:
                    doc.name = os.path.splitext(os.path.basename(doc.file.name))[0]
                    doc.save()

                filters = form.cleaned_data['filters']
                if filters:
                    doc.filters.add(*filters)
                    doc.save()

                request.session["coop_cms_media_doc"] = True

                return HttpResponse("close_popup_and_media_slide")
        else:
            form = AddDocForm()

        return render(
            request,
            'coop_cms/popup_upload_doc.html',
            locals()
        )
    except Exception:
        logger.exception("upload_doc")
        raise
Exemplo n.º 5
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
Exemplo n.º 6
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
Exemplo n.º 7
0
def process_nav_edition(request, tree_id):
    """This handle ajax request sent by the tree component"""
    if request.method == 'POST' and request.is_ajax() and 'msg_id' in request.POST:
        try:
            # Get the current tree
            tree_class = get_navtree_class()
            tree = get_object_or_404(tree_class, id=tree_id)

            # check permissions
            perm_name = "{0}.change_{1}".format(get_model_app(tree_class), get_model_name(tree_class))
            if not request.user.has_perm(perm_name):
                raise PermissionDenied

            functions = (
                view_navnode, rename_navnode, remove_navnode, move_navnode,
                add_navnode, get_suggest_list, navnode_in_navigation,
            )
            supported_msg = {}
            # create a map between message name and handler
            # use the function name as message id
            for fct in functions:
                supported_msg[fct.__name__] = fct

            # Call the handler corresponding to the requested message
            response = supported_msg[request.POST['msg_id']](request, tree)

            # If no exception raise: Success
            response['status'] = 'success'
            response.setdefault('message', 'Ok')  # if no message defined in response, add something

        except KeyError as msg:
            response = {'status': 'error', 'message': "Unsupported message : {0}".format(msg)}
        except PermissionDenied:
            response = {'status': 'error', 'message': "You are not allowed to add a node"}
        except ValidationError as ex:
            response = {'status': 'error', 'message': ' - '.join(ex.messages)}
        except Exception as msg:
            logger.exception("process_nav_edition")
            response = {'status': 'error', 'message': "An error occured : {0}".format(msg)}

        # return the result as json object
        return HttpResponse(json.dumps(response), content_type='application/json')
    raise Http404
Exemplo n.º 8
0
def upload_image(request):
    """upload image"""

    try:
        if not request.user.has_perm("coop_cms.add_image"):
            raise PermissionDenied()

        if request.method == "POST":
            form = AddImageForm(request.POST, request.FILES)
            if form.is_valid():
                src = form.cleaned_data['image']
                description = form.cleaned_data['descr']
                copyright = form.cleaned_data['copyright']
                if not description:
                    description = os.path.splitext(src.name)[0]
                image = models.Image(name=description, copyright=copyright)
                image.size = form.cleaned_data["size"]
                image.file.save(src.name, src)
                image.save()

                filters = form.cleaned_data['filters']
                if filters:
                    image.filters.add(*filters)
                    image.save()

                return HttpResponse("close_popup_and_media_slide")
        else:
            form = AddImageForm()

        return render(
            request,
            'coop_cms/popup_upload_image.html',
            {
                'form': form,
            }
        )
    except Exception:
        logger.exception("upload_image")
        raise
Exemplo n.º 9
0
def upload_image(request):
    """upload image"""

    try:
        if not request.user.has_perm("coop_cms.add_image"):
            raise PermissionDenied()

        if request.method == "POST":
            form = AddImageForm(request.POST, request.FILES)
            if form.is_valid():
                src = form.cleaned_data['image']
                description = form.cleaned_data['descr']
                copyright = form.cleaned_data['copyright']
                if not description:
                    description = os.path.splitext(src.name)[0]
                image = models.Image(name=description, copyright=copyright)
                image.size = form.cleaned_data["size"]
                image.file.save(src.name, src)
                image.save()

                filters = form.cleaned_data['filters']
                if filters:
                    image.filters.add(*filters)
                    image.save()

                return HttpResponse("close_popup_and_media_slide")
        else:
            form = AddImageForm()

        return render(
            request,
            'coop_cms/popup_upload_image.html',
            {
                'form': form,
            }
        )
    except Exception:
        logger.exception("upload_image")
        raise
Exemplo n.º 10
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
Exemplo n.º 11
0
def process_nav_edition(request, tree_id):
    """This handle ajax request sent by the tree component"""
    if request.method == 'POST' and request.is_ajax(
    ) and 'msg_id' in request.POST:
        try:
            # Get the current tree
            tree_class = get_navtree_class()
            tree = get_object_or_404(tree_class, id=tree_id)

            # check permissions
            perm_name = "{0}.change_{1}".format(get_model_app(tree_class),
                                                get_model_name(tree_class))
            if not request.user.has_perm(perm_name):
                raise PermissionDenied

            functions = (
                view_navnode,
                rename_navnode,
                remove_navnode,
                move_navnode,
                add_navnode,
                get_suggest_list,
                navnode_in_navigation,
            )
            supported_msg = {}
            # create a map between message name and handler
            # use the function name as message id
            for fct in functions:
                supported_msg[fct.__name__] = fct

            # Call the handler corresponding to the requested message
            response = supported_msg[request.POST['msg_id']](request, tree)

            # If no exception raise: Success
            response['status'] = 'success'
            response.setdefault(
                'message',
                'Ok')  # if no message defined in response, add something

        except KeyError as msg:
            response = {
                'status': 'error',
                'message': "Unsupported message : {0}".format(msg)
            }
        except PermissionDenied:
            response = {
                'status': 'error',
                'message': "You are not allowed to add a node"
            }
        except ValidationError as ex:
            response = {'status': 'error', 'message': ' - '.join(ex.messages)}
        except Exception as msg:
            logger.exception("process_nav_edition")
            response = {
                'status': 'error',
                'message': "An error occured : {0}".format(msg)
            }

        # return the result as json object
        return HttpResponse(json.dumps(response),
                            content_type='application/json')
    raise Http404
Exemplo n.º 12
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