コード例 #1
0
def delete_dashboard_entry(request, entry_id):
    """
    Remove dashboard entry.

    :param django.http.HttpRequest request:
    :param int entry_id: ID of the dashboard entry to delete.
    :return django.http.HttpResponse:
    """
    try:
        obj = DashboardEntry._default_manager \
                            .select_related('workspace') \
                            .get(pk=entry_id, user=request.user)
        plugin = obj.get_plugin()
        plugin.request = request
        plugin._delete_plugin_data()
        workspace = getattr(obj.workspace, 'slug', None)
        obj.delete()

        if not request.is_ajax():
            messages.info(request, _('The dashboard widget "{0}" was deleted '
                                     'successfully.').format(plugin.name))

        if request.is_ajax():
            return HttpResponse(json.dumps({'success': 1}))
        else:
            # Redirect to dashboard view.
            if workspace:
                return redirect('dash.edit_dashboard', workspace=workspace)
            else:
                return redirect('dash.edit_dashboard')
    except ObjectDoesNotExist as e:
        if request.is_ajax():
            return HttpResponse(json.dumps({'success': 1}))
        raise Http404(e)
コード例 #2
0
ファイル: widgets.py プロジェクト: ykkwon/django-dash
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name
        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"

        mce_config = tinymce_settings.DEFAULT_CONFIG.copy()
        mce_config.update(get_language_config(self.content_language))
        if tinymce_settings.USE_FILEBROWSER:
            mce_config['file_browser_callback'] = "djangoFileBrowser"
        mce_config.update(self.mce_attrs)
        if not 'mode' in mce_config:
            mce_config['mode'] = 'exact'
        if mce_config['mode'] == 'exact':
            mce_config['elements'] = final_attrs['id']
        mce_config['strict_loading_mode'] = 1

        # Fix for js functions
        js_functions = {}
        for k in ('paste_preprocess', 'paste_postprocess'):
            if k in mce_config:
                js_functions[k] = mce_config[k]
                del mce_config[k]
        mce_json = json.dumps(mce_config)

        pos = final_attrs['id'].find('__prefix__')
        if pos != -1:
            mce_json = mce_json.replace('"%s"' % final_attrs['id'], 'elements')

        for k in js_functions:
            index = mce_json.rfind('}')
            mce_json = mce_json[:index] + ', ' + k + ':' + js_functions[
                k].strip() + mce_json[index:]

        html = [
            '<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))
        ]
        if tinymce_settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }
            compressor_json = json.dumps(compressor_config)
            html.append(
                '<script type="text/javascript">tinyMCE_GZ.init(%s)</script>' %
                compressor_json)

        if pos != -1:
            html.append('''<script type="text/javascript">
setTimeout(function () {
    var id = '%s';

    if (typeof(window._tinymce_inited) == 'undefined') {
        window._tinymce_inited = [];
    }

    if (typeof(window._tinymce_inited[id]) == 'undefined') {
        window._tinymce_inited[id] = true;
    } else {
        var elements = id.replace(/__prefix__/, parseInt(document.getElementById('%sTOTAL_FORMS').value) - 1);
        if (document.getElementById(elements)) {
            tinymce.init(%s);
        }
    }
}, 0);
</script>''' % (final_attrs['id'], final_attrs['id'][0:pos], mce_json))
        else:
            html.append(
                '<script type="text/javascript">tinyMCE.init(%s)</script>' %
                mce_json)

        return mark_safe('\n'.join(html))
コード例 #3
0
ファイル: views.py プロジェクト: drellano/django-dash
def add_dashboard_entry(request, placeholder_uid, plugin_uid, workspace=None, \
                        position=None, \
                        template_name='dash/add_dashboard_entry.html', \
                        template_name_ajax='dash/add_dashboard_entry_ajax.html'):
    """
    Add dashboard entry.

    :param django.http.HttpRequest request:
    :param string placeholder_uid: Placeholder UID.
    :param string plugin_uid: Plugin UID.
    :param string workspace: Workspace slug.
    :param int position: If given, provided as position for the
        plugin (conflict resolution should take place).
    :param string template_name:
    :param string template_name_ajax: Template used for AJAX requests.
    :return django.http.HttpResponse:
    """
    # Getting dashboard settings for the user. Then get users' layout.
    dashboard_settings = get_or_create_dashboard_settings(request.user)
    layout = get_layout(
        layout_uid=dashboard_settings.layout_uid, as_instance=True
        )

    if not validate_placeholder_uid(layout, placeholder_uid):
        raise Http404(_("Invalid placeholder: {0}").format(placeholder_uid))

    if not validate_plugin_uid(plugin_uid):
        raise Http404(_("Invalid plugin name: {0}").format(plugin_uid))

    plugin = plugin_registry.get(plugin_uid)(layout.uid, placeholder_uid)
    plugin.request = request

    if plugin.add_form_template:
        template_name = plugin.add_form_template

    # Template context
    context = {
        'layout': layout,
        'dashboard_settings': dashboard_settings
    }

    obj = DashboardEntry()
    obj.layout_uid = layout.uid
    obj.placeholder_uid = placeholder_uid
    obj.plugin_uid = plugin_uid
    obj.user = request.user

    occupied_cells = build_cells_matrix(
            request.user,
            layout,
            placeholder=layout.get_placeholder(placeholder_uid),
            workspace=workspace
            )

    # If plugin has form, it is configurable which means we have to load the
    # plugin form and validate user input.
    plugin_form = plugin.get_form()
    if plugin_form:
        # If POST request and form data is valid, save the data and redirect
        # to the dashboard edit.
        if 'POST' == request.method:
            form = plugin.get_initialised_create_form_or_404(
                data=request.POST, files=request.FILES
                )
            if form.is_valid():
                # Saving the plugin form data.
                form.save_plugin_data(request=request)

                # Getting the plugin data.
                obj.plugin_data = form.get_plugin_data(request=request)

                # Handling the workspace.
                workspace_id = None
                obj.workspace = workspace_id
                if workspace:
                    workspace_slug = slugify_workspace(workspace)
                    workspace_id = DashboardWorkspace.objects.get(name=workspace).pk
                    try:
                        obj.workspace = DashboardWorkspace._default_manager.get(
                            slug = workspace_slug,
                            user = request.user,
                            layout_uid = layout.uid
                            )
                    except ObjectDoesNotExist as e:
                        messages.info(
                            request,
                            _('The workspace with slug "{0}" does not belong to '
                              'layout "{1}".').format(workspace_slug, layout.name)
                            )
                        return redirect('dash.edit_dashboard')

                # If position given, use it.
                try:
                    position = int(position)
                except Exception as e:
                    position = None

                if position:
                    obj.position = position

                # Save the object.
                obj.save()
                if int(position) in occupied_cells:
                    if not DashboardEntry.objects.filter(position=int(position), layout_uid=layout.uid,
                                                         workspace_id=workspace_id,
                                                         plugin_uid__startswith='WidgetSwitcher').exists():
                        pattern = re.compile(r'\d+x\d+')
                        dimensions = pattern.search(str(plugin_uid))
                        switcher = DashboardEntry()
                        switcher.layout_uid = layout.uid
                        switcher.placeholder_uid = placeholder_uid
                        switcher.plugin_uid = 'WidgetSwitcher_'+dimensions.group()
                        switcher.user = request.user
                        switcher.plugin_data = json.dumps({"timer": 10})
                        switcher.position = int(position)
                        switcher.workspace = None
                        if workspace:
                            switcher.workspace = DashboardWorkspace._default_manager.get(
                                    slug=workspace_slug,
                                    user=request.user,
                                    layout_uid=layout.uid
                                    )
                        switcher.save()

                messages.info(request, _('The dashboard widget "{0}" was added '
                                         'successfully.').format(plugin.name))

                # Redirect to the dashboard view.
                if obj.workspace:
                    return redirect(
                        'dash.edit_dashboard', workspace=obj.workspace.slug
                        )
                else:
                    return redirect('dash.edit_dashboard')

        # If POST but data invalid, show the form with errors.
        else:
            form = plugin.get_initialised_create_form_or_404()

        context.update(
            {'form': form, 'plugin_uid': plugin_uid, 'plugin': plugin}
            )

    # If plugin is not configurable, it's just saved as is.
    else:
        obj.save()
        return redirect('dash.edit_dashboard')

    if request.is_ajax():
        template_name = template_name_ajax

    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
        )
コード例 #4
0
    def render(self, name, value, attrs=None):
        """Render."""
        if value is None:
            value = ''

        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs)
        final_attrs['name'] = name

        assert 'id' in final_attrs, "TinyMCE widget attributes must " \
                                    "contain 'id'"

        mce_config = tinymce_settings.DEFAULT_CONFIG.copy()
        mce_config.update(get_language_config(self.content_language))

        if tinymce_settings.USE_FILEBROWSER:
            mce_config['file_browser_callback'] = "djangoFileBrowser"

        mce_config.update(self.mce_attrs)

        if 'mode' not in mce_config:
            mce_config['mode'] = 'exact'

        if mce_config['mode'] == 'exact':
            mce_config['elements'] = final_attrs['id']

        mce_config['strict_loading_mode'] = 1

        # Fix for js functions
        js_functions = {}
        for k in ('paste_preprocess', 'paste_postprocess'):
            if k in mce_config:
                js_functions[k] = mce_config[k]
                del mce_config[k]

        mce_json = json.dumps(mce_config)

        pos = final_attrs['id'].find('__prefix__')
        if pos != -1:
            mce_json = mce_json.replace('"%s"' % final_attrs['id'], 'elements')

        for k in js_functions:
            index = mce_json.rfind('}')
            mce_json = mce_json[:index] + \
                ', ' + \
                k + \
                ':' + \
                js_functions[k].strip() + \
                mce_json[index:]

        html = [
            '<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))
        ]

        if tinymce_settings.USE_COMPRESSOR:
            compressor_config = {
                'plugins': mce_config.get('plugins', ''),
                'themes': mce_config.get('theme', 'advanced'),
                'languages': mce_config.get('language', ''),
                'diskcache': True,
                'debug': False,
            }

            compressor_json = json.dumps(compressor_config)
            html.append(
                '<script type="text/javascript">tinyMCE_GZ.init(%s)'
                '</script>' % compressor_json
            )

        if pos != -1:
            html.append('''<script type="text/javascript">
setTimeout(function () {
    var id = '%s';

    if (typeof(window._tinymce_inited) == 'undefined') {
        window._tinymce_inited = [];
    }

    if (typeof(window._tinymce_inited[id]) == 'undefined') {
        window._tinymce_inited[id] = true;
    } else {
        var elements = id.replace(
            /__prefix__/,
            parseInt(document.getElementById('%sTOTAL_FORMS').value) - 1
        );
        if (document.getElementById(elements)) {
            tinymce.init(%s);
        }
    }
}, 0);
</script>''' % (final_attrs['id'], final_attrs['id'][0:pos], mce_json))

        else:
            html.append('<script type="text/javascript">tinyMCE.init(%s)'
                        '</script>' % mce_json)

        return mark_safe('\n'.join(html))