示例#1
0
    def add_widget(self, obj, item):
        model = item['model']
        title = item['verbose_name']
        func_name = item['function']
        dashboard = item['dashboard']
        list_display = item.get('list_display')
        link = item['link']

        l = []
        if dashboard:
            if type(dashboard) == dict:
                for position, group_names in list(dashboard.items()):
                    group_names = type(
                        group_names) == tuple and group_names or (
                            group_names, )
                    l.append((position, group_names))
            else:
                l.append((dashboard, item['can_view']))

            for position, group_names in l:
                if permissions.check_group_or_permission(
                        self.request, group_names, ignore_superuser=True):
                    func = getattr(obj, func_name)
                    f_return = execute_and_format(self.request, func)

                    if type(f_return) in (int, Decimal):
                        verbose_name = get_metadata(model,
                                                    'verbose_name_plural')
                        icon = get_metadata(model, 'icon')
                        panel = NumberPanel(self.request, verbose_name,
                                            f_return, title, icon)
                        html = str(panel)

                    elif hasattr(f_return, 'model'):
                        compact = position in ('left', 'right')
                        app_label = get_metadata(model, 'app_label')
                        model_name = model.__name__.lower()
                        verbose_name_plural = get_metadata(
                            model, 'verbose_name_plural')
                        if link:
                            title = '{} {}'.format(verbose_name_plural, title)
                        url = '/list/{}/{}/{}/'.format(app_label, model_name,
                                                       func_name)
                        paginator = Paginator(self.request,
                                              f_return,
                                              title,
                                              readonly=compact,
                                              list_display=list_display,
                                              list_filter=(),
                                              search_fields=(),
                                              list_subsets=[func_name],
                                              url=link and url or None)
                        if compact and not paginator.template:
                            paginator.column_names = paginator.column_names[
                                0:1]
                        html = str(paginator)
                    else:
                        html = str(f_return)
                    self.add(html, position)
示例#2
0
    def load_widgets(self):
        from djangoplus.cache import CACHE
        for model in CACHE['SUBSETS']:
            notification_panels = {}
            icon = get_metadata(model, 'icon', 'fa-bell-o')
            title = get_metadata(model, 'verbose_name_plural')
            app_label = get_metadata(model, 'app_label')
            model_name = model.__name__.lower()
            for item in CACHE['SUBSETS'][model]:
                description = item['verbose_name']
                notify = item['notify']
                if notify is True or notify and permissions.check_group_or_permission(
                        self.request, notify):
                    attr_name = item['function'].__func__.__name__
                    qs = model.objects.all(self.request.user)
                    qs = getattr(qs, attr_name)()
                    count = qs.count()
                    if count:
                        url = '/list/{}/{}/{}/'.format(app_label, model_name,
                                                       attr_name)
                        if model_name in notification_panels:
                            notification_panel = notification_panels[
                                model_name]
                        else:
                            notification_panel = NotificationPanel(
                                self.request, title, icon)
                            self.right.append(notification_panel)
                            notification_panels[
                                model_name] = notification_panel
                        notification_panel.add(count, url, description)

        for model in CACHE['LIST_DASHBOARD']:
            title = get_metadata(model, 'verbose_name_plural')
            position = get_metadata(model, 'dashboard')
            paginator = Paginator(self.request,
                                  model.objects.all(self.request.user), title)
            self.add(paginator, position)

        icon_panel = ShortcutPanel(self.request)
        card_panel = CardPanel(self.request)

        self.top.append(icon_panel)
        self.center.append(card_panel)

        for item in CACHE['SUBSET_WIDGETS']:
            self.add_widget(item['model'].objects.all(self.request.user), item)

        for item in CACHE['WIDGETS']:
            if permissions.check_group_or_permission(self.request,
                                                     item['can_view'],
                                                     ignore_superuser=True):
                func = item['function']
                position = item['position']
                f_return = func(self.request)
                html = render_to_string(
                    ['{}.html'.format(func.__name__), 'dashboard.html'],
                    f_return, self.request)
                self.add(html, position)
示例#3
0
def listt(request, app, cls, subset=None):

    try:
        _model = apps.get_model(app, cls)
    except LookupError as e:
        return page_not_found(request, e, 'error404.html')
    title = get_metadata(_model, 'verbose_name_plural')
    subsetp = None
    list_display = None
    list_filter = None
    search_fields = None
    if subset:
        subset_func = getattr(_model.objects.get_queryset(), subset)
        can_view = get_metadata(subset_func, 'can_view')
        list_display = get_metadata(subset_func, 'list_display')
        list_filter = get_metadata(subset_func, 'list_filter')
        search_fields = get_metadata(subset_func, 'search_fields')
        title = '{} - {}'.format(title,
                                 get_metadata(subset_func, 'verbose_name'))
    else:
        tid = request.GET.get('tid')
        subsetp = request.GET.get('tab{}'.format(tid))
        if tid and subsetp:
            subset_func = getattr(_model.objects.get_queryset(), subsetp)
            subset_title = get_metadata(subset_func, 'verbose_name')
            can_view = get_metadata(subset_func, 'can_view')
            title = '{} - {}'.format(title,
                                     get_metadata(subset_func, 'verbose_name'))
            if not permissions.check_group_or_permission(request, can_view):
                return httprr(
                    request,
                    '/admin/login/?next={}'.format(request.get_full_path()))
        else:
            permission = '{}.list_{}'.format(app, cls)
            if not request.user.has_perm(permission):
                return httprr(
                    request,
                    '/admin/login/?next={}'.format(request.get_full_path()))

    qs = _model.objects.all(request.user)
    list_subsets = subset and [subset] or None

    paginator = Paginator(request,
                          qs,
                          title,
                          list_subsets=list_subsets,
                          is_list_view=True,
                          list_display=list_display,
                          list_filter=list_filter,
                          search_fields=search_fields)
    paginator.process_request()

    paginator.load_actions()
    return render(request, 'default.html', locals())
示例#4
0
def log(request, app, cls, pk=None):
    try:
        _model = apps.get_model(app, cls)
    except LookupError as e:
        return page_not_found(request, e, 'error404.html')

    if pk:
        obj = _model.objects.get(pk=pk)
        qs = obj.get_logs()
        title = 'Log - {}'.format(obj)
    else:
        content_type = ContentType.objects.get_for_model(_model)
        qs = content_type.log_set.all()
        title = 'Logs - {}'.format(get_metadata(_model, 'verbose_name_plural'))

    paginator = Paginator(request, qs, 'Log')
    return render(request, 'default.html', locals())
示例#5
0
    def get_component(self, request, as_pdf=False):
        verbose_name = getattr(self.relation_model, '_meta').verbose_name
        if self.is_one_to_one or self.is_many_to_one:
            panel_fieldsets = getattr(self.relation_model, 'fieldsets', None)
            if panel_fieldsets:
                panel_fieldsets = ((self.relation_verbose_name, panel_fieldsets[0][1]),)
            else:
                panel_fieldsets = get_fieldsets(self.relation_model, self.relation_verbose_name)
            component = ModelPanel(
                request, self.relation_value or self.relation_model(),
                fieldsets=panel_fieldsets, complete=False
            )
            if self.view_url and permissions.has_view_permission(request, self.relation_model):
                label = 'Detalhar {}'.format(verbose_name)
                component.drop_down.add_action(label, self.view_url, 'ajax', 'fa-eye', category=label)
            if self.add_url and permissions.has_edit_permission(request, self.model):
                label = 'Atualizar {}'.format(verbose_name)
                component.drop_down.add_action(label, self.add_url, 'popup', 'fa-edit', category=label)
            if self.delete_url and permissions.has_edit_permission(request, self.model):
                label = 'Excluir {}'.format(verbose_name)
                component.drop_down.add_action(label, self.delete_url, 'popup', 'fa-close', category=label)
        else:
            inlines = []
            fieldsets = getattr(self.model, 'fieldsets', ())
            title = self.relation_verbose_name
            for fieldset in fieldsets:
                fieldset_relations = fieldset[1].get('relations', ())
                fieldset_inlines = fieldset[1].get('inlines', ())
                fieldset_fields = fieldset[1].get('fields', ())
                for inline in fieldset_inlines:
                    inlines.append(inline)
                is_relation = self.relation_name in fieldset_relations
                is_inline = self.relation_name in fieldset_inlines
                is_field = self.relation_name in fieldset_fields
                if is_relation or is_inline or is_field:
                    if len(fieldset_relations) + len(fieldset_inlines) + len(fieldset_fields) == 1:
                        title = fieldset[0].split('::')[-1]

            if self.is_one_to_many or self.is_many_to_many:
                if self.can_add:
                    has_add_permission = permissions.check_group_or_permission(request, self.can_add)
                else:
                    has_add_permission = permissions.has_add_permission(request, self.model)
            else:
                has_add_permission = permissions.has_add_permission(request, self.relation_model)

            list_subsets = list(self.subsets.keys())
            component = Paginator(
                request, self.relation_value.all(request.user), title, relation=self,
                list_subsets=list_subsets, readonly=not has_add_permission, uid=slugify(self.relation_name)
            )
            action_names = self.subsets.get(component.current_tab or 'all', [])
            component.load_actions(action_names)
            instance = self.relation_model()
            if self.hidden_field_name:
                setattr(instance, self.hidden_field_name, self.instance)
            can_add = not hasattr(instance, 'can_add') or instance.can_add()

            if self.add_url and has_add_permission and can_add:
                if self.relation_name in inlines:
                    form_name = get_metadata(self.relation_model, 'add_form')
                    relation_verbose_name = get_metadata(self.relation_model, 'verbose_name')
                    if form_name:
                        fromlist = list(map(str, [get_metadata(self.relation_model, 'app_label')]))
                        module = __import__('{}.forms'.format(fromlist), fromlist=fromlist)
                        form_cls = getattr(module, form_name)
                    else:
                        class Form(ModelForm):
                            class Meta:
                                model = self.relation_model
                                fields = get_metadata(self.relation_model, 'form_fields', '__all__')
                                exclude = get_metadata(self.relation_model, 'exclude_fields', ())
                                submit_label = 'Adicionar'
                                title = 'Adicionar {}'.format(relation_verbose_name)

                        form_cls = Form
                    form = form_cls(request, instance=instance, inline=True)
                    if self.hidden_field_name in form.fields:
                        del (form.fields[self.hidden_field_name])
                    if not hasattr(form.instance, 'can_add') or form.instance.can_add():
                        component.form = form
                        if form.is_valid():
                            try:
                                form.save()
                                component.message = 'Ação realizada com sucesso'
                            except ValidationError as e:
                                form.add_error(None, str(e.message))
                else:
                    add_label = self.add_label or get_metadata(self.relation_model, 'add_label')
                    label = add_label or 'Adicionar {}'.format(verbose_name)
                    component.add_action(label, self.add_url, 'popup', 'fa-plus')

        component.as_pdf = as_pdf

        return component
示例#6
0
def listt(request, app, cls, subset=None):

    try:
        _model = apps.get_model(app, cls)
    except LookupError as e:
        return page_not_found(request, e, 'error404.html')
    title = get_metadata(_model, 'verbose_name_plural')
    subsetp = None
    list_display = None
    list_filter = None
    search_fields = None
    if subset:
        subset_func = getattr(_model.objects.get_queryset(), subset)
        can_view = subset_func._metadata['{}:can_view'.format(subset)]
        list_display = subset_func._metadata['{}:list_display'.format(subset)]
        list_filter = subset_func._metadata['{}:list_filter'.format(subset)]
        search_fields = subset_func._metadata['{}:search_fields'.format(
            subset)]
        title = '{} - {}'.format(
            title, subset_func._metadata['{}:title'.format(subset)])
    else:
        tid = request.GET.get('tid')
        subsetp = request.GET.get('tab{}'.format(tid))
        if tid and subsetp:
            subset_func = getattr(_model.objects.get_queryset(), subsetp)
            subset_title = subset_func._metadata['{}:title'.format(subsetp)]
            can_view = subset_func._metadata['{}:can_view'.format(subsetp)]
            title = '{} - {}'.format(
                title, subset_func._metadata['{}:title'.format(subsetp)])
            if not permissions.check_group_or_permission(request, can_view):
                return httprr(
                    request,
                    '/admin/login/?next={}'.format(request.get_full_path()))
        else:
            permission = '{}.list_{}'.format(app, cls)
            if not request.user.has_perm(permission):
                return httprr(
                    request,
                    '/admin/login/?next={}'.format(request.get_full_path()))

    qs = _model.objects.all(request.user)
    list_subsets = subset and [subset] or None

    paginator = Paginator(request,
                          qs,
                          title,
                          list_subsets=list_subsets,
                          is_list_view=True,
                          list_display=list_display,
                          list_filter=list_filter,
                          search_fields=search_fields)
    paginator.process_request()

    if _model in loader.class_actions:
        for group in loader.class_actions[_model]:
            for view_name in loader.class_actions[_model][group]:
                _action = loader.class_actions[_model][group][view_name]
                action_title = _action['title']
                action_message = _action['message']
                action_can_execute = _action['can_execute']
                action_input = _action['input']
                action_css = _action['css']
                action_condition = _action['condition']
                initial = _action['initial']
                choices = _action['choices']

                if subsetp:
                    if subsetp not in loader.subset_actions[
                            _model] or view_name not in loader.subset_actions[
                                _model][subsetp]:
                        continue
                else:
                    if subset not in loader.subset_actions[
                            _model] or view_name not in loader.subset_actions[
                                _model][subset]:
                        continue

                if permissions.check_group_or_permission(
                        request, action_can_execute):
                    func = hasattr(qs, view_name) and getattr(
                        qs, view_name) or None
                    if func:

                        char = '?' in request.get_full_path() and '&' or '?'
                        url = '{}{}{}'.format(request.get_full_path(), char,
                                              '{}='.format(view_name))

                        has_input = func.__code__.co_argcount > 1

                        if not has_input:
                            action_css = action_css.replace('popup', '')
                        paginator.add_subset_action(action_title, url,
                                                    action_css, None,
                                                    action_condition)

                        if view_name in request.GET:
                            ids = paginator.get_selected_ids()
                            if ids:
                                qs = paginator.get_queryset(
                                    paginate=False).filter(id__in=ids)
                            else:
                                qs = paginator.get_queryset(paginate=False)

                            func = getattr(qs, view_name)
                            redirect_url = None

                            if has_input:
                                form = factory.get_class_action_form(
                                    request, _model, _action, func)
                                paginator = ''
                                if form.is_valid():
                                    params = []
                                    for param in func.__code__.co_varnames[
                                            1:func.__code__.co_argcount]:
                                        if param in form.cleaned_data:
                                            params.append(
                                                form.cleaned_data[param])
                                    try:
                                        f_return = func(*params)
                                        redirect_url = '..'
                                    except ValidationError as e:
                                        form.add_error(None, str(e.message))
                                if not redirect_url:
                                    return render(request, 'default.html',
                                                  locals())
                            else:
                                f_return = func()
                                redirect_url = '.'

                            if redirect_url:
                                request.GET._mutable = True
                                del request.GET['ids']
                                del request.GET[view_name]
                                request.GET._mutable = False
                            return httprr(request, redirect_url,
                                          action_message)
                    else:
                        url = '/{}/{}/'.format(app, view_name)
                        if view_name in request.GET:
                            return httprr(request, url)
                        else:
                            action_css = action_css.replace('popup', '')
                            paginator.add_action(action_title, url, action_css,
                                                 None)

    paginator.add_actions()
    return render(request, 'default.html', locals())
示例#7
0
    def __init__(self, request):

        super(DashboardPanel, self).__init__('dashboard', request)
        self.top = []
        self.center = []
        self.left = []
        self.right = []
        self.bottom = []

        from djangoplus.cache import loader
        for model in loader.subsets:
            icon = get_metadata(model, 'icon', 'fa-bell-o')
            title = get_metadata(model, 'verbose_name_plural')
            app_label = get_metadata(model, 'app_label')
            model_name = model.__name__.lower()
            for item in loader.subsets[model]:
                description = item['title']
                can_view = item['can_view']
                notify = item['notify']
                if notify and permissions.check_group_or_permission(
                        request, can_view):
                    attr_name = item['function'].__func__.__name__
                    qs = model.objects.all(request.user)
                    qs = getattr(qs, attr_name)()
                    count = qs.count()
                    if count:
                        url = '/list/{}/{}/{}/'.format(app_label, model_name,
                                                       attr_name)
                        notification_panel = NotificationPanel(
                            request, title, count, url, description, icon)
                        self.right.append(notification_panel)

        icon_panel = ShortcutPanel(request)
        card_panel = CardPanel(request)

        self.top.append(icon_panel)
        self.center.append(card_panel)

        for item in loader.subset_widgets:

            model = item['model']
            title = item['title']
            function = item['function']
            dashboard = item['dashboard']
            formatter = item['formatter']
            list_display = item.get('list_display')
            link = item['link']

            l = []
            if type(dashboard) == dict:
                for position, group_names in list(dashboard.items()):
                    group_names = type(
                        group_names) == tuple and group_names or (
                            group_names, )
                    l.append((position, group_names))
            else:
                l.append((dashboard, item['can_view']))

            for position, group_names in l:
                if permissions.check_group_or_permission(
                        request, group_names, ignore_superuser=True):
                    qs = model.objects.all(request.user)
                    f_return = getattr(qs, function)()
                    html = ''

                    if type(f_return) in (int, Decimal):
                        verbose_name = get_metadata(model,
                                                    'verbose_name_plural')
                        icon = get_metadata(model, 'icon')
                        panel = NumberPanel(request, verbose_name, f_return,
                                            title, icon)
                        html = str(panel)

                    if type(f_return
                            ).__name__ == 'QueryStatistics' and not formatter:
                        formatter = 'statistics'

                    if formatter:
                        func = loader.formatters[formatter]
                        if len(func.__code__.co_varnames) == 1:
                            html = str(func(f_return))
                        else:
                            html = str(
                                func(f_return,
                                     request=self.request,
                                     verbose_name=title))
                    elif hasattr(f_return, 'model'):
                        compact = position in ('left', 'right')
                        app_label = get_metadata(model, 'app_label')
                        model_name = model.__name__.lower()
                        verbose_name_plural = get_metadata(
                            model, 'verbose_name_plural')
                        if link:
                            title = '{} {}'.format(verbose_name_plural, title)
                        url = '/list/{}/{}/{}/'.format(app_label, model_name,
                                                       function)
                        paginator = Paginator(self.request,
                                              f_return,
                                              title,
                                              readonly=compact,
                                              list_display=list_display,
                                              list_filter=(),
                                              search_fields=(),
                                              list_subsets=[function],
                                              url=link and url or None)
                        if compact:
                            paginator.column_names = paginator.column_names[
                                0:1]
                        html = str(paginator)

                    if position == 'top':
                        self.top.append(html)
                    elif position == 'center':
                        self.center.append(html)
                    elif position == 'left':
                        self.left.append(html)
                    elif position == 'right':
                        self.right.append(html)
                    elif position == 'bottom':
                        self.bottom.append(html)

        for item in loader.widgets:
            if permissions.check_group_or_permission(request,
                                                     item['can_view'],
                                                     ignore_superuser=True):
                function = item['function']
                position = item['position']
                f_return = function(request)
                html = render_to_string(
                    ['{}.html'.format(function.__name__), 'dashboard.html'],
                    f_return, request)
                if position == 'top':
                    self.top.append(html)
                elif position == 'center':
                    self.center.append(html)
                elif position == 'left':
                    self.left.append(html)
                elif position == 'right':
                    self.right.append(html)
                elif position == 'bottom':
                    self.bottom.append(html)
示例#8
0
def listt(request, app, cls, subset=None):

    try:
        _model = apps.get_model(app, cls)
    except LookupError:
        return page_not_found(request)
    subsetp = None
    if subset:
        subset_func = getattr(_model.objects.all(), subset)
        can_view = subset_func._metadata['%s:can_view' % subset]
    else:
        tid = request.GET.get('tid')
        subsetp = request.GET.get('tab%s' % tid)
        if tid and subsetp:
            subset_func = getattr(_model.objects.get_queryset(), subsetp)
            can_view = subset_func._metadata['%s:can_view' % subsetp]
            if not permissions.check_group_or_permission(request, can_view):
                return httprr(
                    request, '/admin/login/?next=%s' % request.get_full_path())
        else:
            permission = '%s.list_%s' % (app, cls)
            if not request.user.has_perm(permission):
                return httprr(
                    request, '/admin/login/?next=%s' % request.get_full_path())

    qs = _model.objects.all(request.user)
    list_subsets = subset and [subset] or None
    if subset:
        title = getattr(getattr(qs, subset), '_metadata')['%s:title' % subset]

    else:
        title = u'%s' % get_metadata(_model, 'verbose_name_plural')

    paginator = Paginator(request,
                          qs,
                          title,
                          list_subsets=list_subsets,
                          is_list_view=True)
    response = paginator.get_response()
    if response:
        return response

    if _model in loader.class_actions:
        for group in loader.class_actions[_model]:
            for view_name in loader.class_actions[_model][group]:
                _action = loader.class_actions[_model][group][view_name]
                action_title = _action['title']
                action_message = _action['message']
                action_can_execute = _action['can_execute']
                action_input = _action['input']
                action_css = _action['css']
                action_condition = _action['condition']
                initial = _action['initial']
                choices = _action['choices']

                if subsetp:
                    if subsetp not in loader.subset_actions[
                            _model] or view_name not in loader.subset_actions[
                                _model][subsetp]:
                        continue
                else:
                    if subset not in loader.subset_actions[
                            _model] or view_name not in loader.subset_actions[
                                _model][subset]:
                        continue

                if permissions.check_group_or_permission(
                        request, action_can_execute):
                    func = hasattr(qs, view_name) and getattr(
                        qs, view_name) or None
                    if func:

                        char = '?' in request.get_full_path() and '&' or '?'
                        url = '%s%s%s' % (request.get_full_path(), char,
                                          '%s=' % view_name)

                        has_input = func.func_code.co_argcount > 1

                        if not has_input:
                            action_css = action_css.replace('popup', '')
                        paginator.add_subset_action(action_title, url,
                                                    action_css, None,
                                                    action_condition)

                        if view_name in request.GET:
                            ids = paginator.get_selected_ids()
                            if ids:
                                qs = paginator.get_queryset(
                                    paginate=False).filter(id__in=ids)
                            else:
                                qs = paginator.get_queryset(paginate=False)

                            func = getattr(qs, view_name)
                            redirect_url = None

                            if has_input:
                                form = factory.get_class_action_form(
                                    request, _model, _action, func)
                                paginator = ''
                                if form.is_valid():
                                    params = []
                                    for param in func.func_code.co_varnames[
                                            1:func.func_code.co_argcount]:
                                        if param in form.cleaned_data:
                                            params.append(
                                                form.cleaned_data[param])
                                    try:
                                        f_return = func(*params)
                                        redirect_url = '..'
                                    except ValidationError, e:
                                        form.add_error(None,
                                                       unicode(e.message))
                                if not redirect_url:
                                    return render(request, 'default.html',
                                                  locals())
                            else:
                                f_return = func()
                                redirect_url = '.'

                            if redirect_url:
                                request.GET._mutable = True
                                del request.GET['ids']
                                del request.GET[view_name]
                                request.GET._mutable = False
                            return httprr(request, redirect_url,
                                          action_message)
                    else:
                        url = '/%s/%s/' % (app, view_name)
                        if view_name in request.GET:
                            return httprr(request, url)
                        else:
                            action_css = action_css.replace('popup', '')
                            paginator.add_action(action_title, url, action_css,
                                                 None)
示例#9
0
    def __init__(self, request):
        from djangoplus.cache import loader
        super(DashboardPanel, self).__init__(request)
        self.top = []
        self.center = []
        self.left = []
        self.right = []
        self.bottom = []

        from djangoplus.cache import loader
        for model in loader.subsets:
            icon = get_metadata(model, 'icon', u'fa-bell-o')
            title = get_metadata(model, 'verbose_name_plural')
            app_label = get_metadata(model, 'app_label')
            model_name = model.__name__.lower()
            for item in loader.subsets[model]:
                description = item['title']
                can_view = item['can_view']
                notify = item['notify']
                if notify and permissions.check_group_or_permission(
                        request, can_view):
                    attr_name = item['function'].im_func.func_name
                    qs = model.objects.all(request.user)
                    qs = getattr(qs, attr_name)()
                    count = qs.count()
                    if count:
                        url = '/list/%s/%s/%s/' % (app_label, model_name,
                                                   attr_name)
                        notification_panel = NotificationPanel(
                            request, title, count, url, description, icon)
                        self.right.append(notification_panel)

        icon_panel = IconPanel(request)
        card_panel = CardPanel(request)

        self.top.append(icon_panel)
        self.center.append(card_panel)

        for item in loader.widgets:
            if permissions.check_group_or_permission(request,
                                                     item['can_view']):
                function = item['function']
                position = item['position']
                f_return = function(request)
                html = render_to_string(
                    ['%s.html' % function.func_name, 'widget.html'], f_return,
                    request)
                if position == 'top':
                    self.top.append(html)
                elif position == 'center':
                    self.center.append(html)
                elif position == 'left':
                    self.left.append(html)
                elif position == 'right':
                    self.right.append(html)
                elif position == 'bottom':
                    self.bottom.append(html)
        for item in loader.subset_widgets:
            if permissions.check_group_or_permission(request,
                                                     item['can_view']):
                model = item['model']
                title = item['title']
                function = item['function']
                position = item['position']
                formatter = item['formatter']
                qs = model.objects.all()
                qs.user = request.user
                f_return = getattr(qs, function)()
                html = ''

                if type(f_return) in (int, Decimal):
                    verbose_name = get_metadata(model, 'verbose_name_plural')
                    icon = get_metadata(model, 'icon')
                    panel = NumberPanel(request, verbose_name, f_return, title,
                                        icon)
                    html = unicode(panel)

                if type(f_return
                        ).__name__ == 'QueryStatistics' and not formatter:
                    formatter = 'statistics'

                if formatter:
                    func = loader.formatters[formatter]
                    if len(func.func_code.co_varnames) == 1:
                        html = unicode(func(f_return))
                    else:
                        html = unicode(
                            func(f_return,
                                 request=self.request,
                                 verbose_name=title))
                elif hasattr(f_return, 'model'):
                    paginator = Paginator(self.request,
                                          f_return,
                                          title,
                                          readonly=True,
                                          list_filter=(),
                                          search_fields=())
                    html = unicode(paginator)

                if position == 'top':
                    self.top.append(html)
                elif position == 'center':
                    self.center.append(html)
                elif position == 'left':
                    self.left.append(html)
                elif position == 'right':
                    self.right.append(html)
                elif position == 'bottom':
                    self.bottom.append(html)
示例#10
0
    def __init__(self,
                 request,
                 obj,
                 current_tab=None,
                 parent=None,
                 fieldsets=None,
                 complete=True):

        super(ModelPanel, self).__init__(request=request)

        self.obj = obj
        self.request = request
        self.title = unicode(obj)
        self.tabs = []
        self.current_tab = current_tab
        self.message = None
        self.complete = complete
        self.drop_down = None
        fieldsets = fieldsets or get_metadata(type(obj), 'view_fieldsets', [])
        if not fieldsets:
            fields = []
            for field in get_metadata(type(obj), 'fields')[1:]:
                fields.append(field.name)

            for field in get_metadata(type(obj), 'local_many_to_many'):
                fields.append(field.name)

            fieldsets = ((u'Dados Gerais', dict(fields=fields)), )

        if self.complete:
            self.drop_down = ModelDropDown(self.request, type(self.obj))
            self.drop_down.add_actions(self.obj, fieldset_title='')
        else:
            self.drop_down = GroupDropDown(self.request)

        self.fieldsets_with_tab_name = []
        self.fieldsets_without_tab_name = []

        model = type(self.obj)
        obj.as_pdf = self.as_pdf

        for fieldset in fieldsets:
            title, info = fieldset
            tab_name = None

            drop_down = ModelDropDown(self.request, model)
            fieldset_actions = info.get('actions', [])

            if fieldset_actions:
                drop_down.add_actions(self.obj, fieldset_title=title)

            if '::' in title:
                tab_name, title = title.split('::')
                url = '/view/%s/%s/%s/%s/' % (get_metadata(
                    model, 'app_label'), model.__name__.lower(), self.obj.pk,
                                              slugify(tab_name))
                tab = (tab_name, url)
                if not self.tabs and not self.current_tab:
                    self.current_tab = slugify(tab_name)
                if tab not in self.tabs:
                    self.tabs.append(tab)

            if not tab_name or slugify(
                    tab_name) == self.current_tab or self.as_pdf:

                fieldset_dict = dict(title=title or u'Dados Gerais',
                                     tab_name=tab_name,
                                     fields=[],
                                     paginators=[],
                                     drop_down=drop_down,
                                     image=None)
                relations = fieldset[1].get('relations', [])

                if tab_name or self.as_pdf:
                    self.fieldsets_with_tab_name.append(fieldset_dict)
                else:
                    self.fieldsets_without_tab_name.append(fieldset_dict)

                if 'can_view' in fieldset[1]:
                    can_view = fieldset[1]['can_view']
                    if not permissions.check_group_or_permission(
                            self.request, can_view):
                        continue

                if 'condition' in fieldset[1]:
                    condition = fieldset[1]['condition']
                    self.obj.request = self.request
                    if not check_condition(condition, self.obj):
                        continue

                if 'image' in fieldset[1]:
                    fieldset_dict['image'] = fieldset[1]['image']

                if 'fields' in fieldset[1]:
                    for name_or_tuple in fieldset[1]['fields']:

                        if not type(name_or_tuple) == tuple:
                            name_or_tuple = (name_or_tuple, )
                        attr_names = []

                        for attr_name in name_or_tuple:
                            if attr_name != parent:
                                attr = getattr(model, attr_name)
                                field = None
                                if hasattr(attr, 'field_name'):
                                    field = getattr(model, '_meta').get_field(
                                        attr.field_name)
                                elif hasattr(attr, 'field'):
                                    field = attr.field
                                if not field or not hasattr(
                                        field, 'display') or field.display:
                                    if is_one_to_one(
                                            model, attr_name
                                    ) and attr.field.display == 'detail':
                                        relations.append(attr_name)
                                    elif is_one_to_many(
                                            model, attr_name
                                    ) and field.display == 'detail':
                                        relations.append(attr_name)
                                    elif is_many_to_one(
                                            model, attr_name
                                    ) and field.display == 'detail':
                                        relations.append(attr_name)
                                    elif is_many_to_many(
                                            model, attr_name) and (
                                                not hasattr(field, 'display')
                                                or field.display == 'detail'):
                                        relations.append(attr_name)
                                    elif is_one_to_many_reverse(
                                            model, attr_name):
                                        relations.append(attr_name)
                                    else:
                                        verbose_name, lookup, sortable, to = get_fiendly_name(
                                            model, attr_name, as_tuple=True)
                                        if to and not should_filter_or_display(
                                                self.request, model, to):
                                            continue
                                        attr_names.append(
                                            dict(verbose_name=verbose_name,
                                                 name=attr_name))
                        if attr_names:
                            fieldset_dict['fields'].append(attr_names)

                if self.complete:

                    for relation_name in relations:
                        if relation_name in [
                                field.name
                                for field in get_metadata(model, 'get_fields')
                        ]:
                            relation_field = find_field_by_name(
                                model, relation_name)
                            relation = getattr(self.obj, relation_name)
                            if not relation and hasattr(
                                    relation_field,
                                    'rel') and relation_field.rel.to:
                                relation = relation_field.rel.to()
                            if hasattr(relation.__class__, 'pk'):
                                if relation.pk:
                                    fieldset_title = relation_field.verbose_name
                                    panel_fieldsets = get_metadata(
                                        type(relation), 'view_fieldsets', [])
                                    panel_fieldsets = (
                                        (fieldset_title,
                                         panel_fieldsets[0][1]), )
                                    panel = ModelPanel(
                                        request,
                                        relation,
                                        fieldsets=panel_fieldsets,
                                        complete=False)

                                    if is_one_to_one(model, relation_name):
                                        app_label = get_metadata(
                                            model, 'app_label')
                                        model_name = model.__name__.lower()
                                        related_model_name = type(
                                            relation).__name__.lower()
                                        add_url = '/add/%s/%s/%s/%s' % (
                                            app_label, model_name, self.obj.pk,
                                            relation_name)
                                        delete_url = None
                                        if relation.pk:
                                            add_url = '%s/%s/' % (add_url,
                                                                  relation.pk)
                                            app_label = get_metadata(
                                                type(relation), 'app_label')
                                            delete_url = '/delete/%s/%s/%s/' % (
                                                app_label, related_model_name,
                                                relation.pk)
                                        if permissions.has_add_permission(
                                                self.request, model
                                        ) or permissions.has_edit_permission(
                                                self.request, model):
                                            if delete_url:
                                                panel.drop_down.add_action(
                                                    'Excluir %s' %
                                                    relation_field.
                                                    verbose_name, delete_url,
                                                    'popup', 'fa-close', None)
                                            panel.drop_down.add_action(
                                                'Atualizar %s' %
                                                relation_field.verbose_name,
                                                add_url, 'popup', 'fa-edit')

                                    fieldset_dict['paginators'].append(panel)
                            else:
                                fieldset_title = len(
                                    relations
                                ) > 1 and title or relation_field.verbose_name

                                if is_one_to_many(
                                        model,
                                        relation_name) or is_many_to_many(
                                            model, relation_name):
                                    to = model.__name__.lower()
                                else:
                                    to = relation_name

                                related_paginator = Paginator(
                                    self.request,
                                    relation.all(),
                                    title=fieldset_title,
                                    to=to,
                                    list_subsets=[])

                                add_url = '/add/%s/%s/%s/%s/' % (get_metadata(
                                    model, 'app_label'), model.__name__.lower(
                                    ), self.obj.pk, relation_name)
                                if permissions.has_add_permission(
                                        self.request, model
                                ) or permissions.has_relate_permission(
                                        self.request, model):
                                    related_paginator.add_action(
                                        'Adicionar %s' % unicode(
                                            get_metadata(
                                                relation.model,
                                                'verbose_name')), add_url,
                                        'popup', 'fa-plus')
                                fieldset_dict['paginators'].append(
                                    related_paginator)
                        else:
                            is_object_set = False
                            for related_object in list_related_objects(model):
                                if relation_name == related_object.get_accessor_name(
                                ):
                                    is_object_set = True
                                    break
                            relation = getattr(self.obj, relation_name)
                            if hasattr(relation, 'all'):
                                qs = relation.all()
                            elif hasattr(relation, '__call__'):
                                qs = relation()
                            else:
                                qs = relation
                            to = is_object_set and related_object.field.name or None

                            fieldset_title = len(
                                relations) > 1 and get_metadata(
                                    qs.model, 'verbose_name_plural') or title

                            if hasattr(relation, '_metadata'):
                                fieldset_title = relation._metadata[
                                    '%s:verbose_name' % relation_name]

                            exclude = [
                                is_object_set and related_object.field.name
                                or ''
                            ]

                            related_paginator = Paginator(
                                self.request,
                                qs,
                                fieldset_title,
                                exclude=exclude,
                                list_subsets=[],
                                to=to,
                                readonly=not is_object_set)
                            if is_object_set and (
                                    permissions.has_add_permission(
                                        self.request, qs.model)
                                    or permissions.has_relate_permission(
                                        self.request, qs.model)):
                                instance = qs.model()
                                setattr(instance, related_object.field.name,
                                        self.obj)
                                if permissions.can_add(self.request, instance):
                                    add_inline = get_metadata(
                                        qs.model, 'add_inline')
                                    if add_inline:
                                        form_name = get_metadata(
                                            qs.model, 'add_form')
                                        if form_name:
                                            fromlist = get_metadata(
                                                qs.model, 'app_label')
                                            forms_module = __import__(
                                                '%s.forms' % fromlist,
                                                fromlist=fromlist)
                                            Form = getattr(
                                                forms_module, form_name)
                                        else:

                                            class Form(ModelForm):
                                                class Meta:
                                                    model = qs.model
                                                    fields = get_metadata(
                                                        qs.model,
                                                        'form_fields',
                                                        '__all__')
                                                    exclude = get_metadata(
                                                        qs.model,
                                                        'exclude_fields', ())
                                                    submit_label = 'Adicionar'
                                                    title = u'Adicionar %s' % get_metadata(
                                                        qs.model,
                                                        'verbose_name')

                                        form = Form(self.request,
                                                    instance=instance,
                                                    inline=True)
                                        if related_object.field.name in form.fields:
                                            del (form.fields[
                                                related_object.field.name])
                                        related_paginator.form = form
                                        if form.is_valid():
                                            try:
                                                form.save()
                                                self.message = u'Ação realizada com sucesso'
                                            except ValidationError, e:
                                                form.add_error(
                                                    None, unicode(e.message))
                                    else:
                                        add_url = '/add/%s/%s/%s/%s/' % (
                                            get_metadata(model, 'app_label'),
                                            model.__name__.lower(),
                                            self.obj.pk,
                                            relation_name.replace('_set', ''))
                                        add_label = u'Adicionar %s' % get_metadata(
                                            qs.model, 'verbose_name')
                                        add_label = get_metadata(
                                            qs.model, 'add_label', add_label)
                                        related_paginator.add_action(
                                            add_label, add_url, 'popup',
                                            'fa-plus')

                            fieldset_dict['paginators'].append(
                                related_paginator)

                if 'extra' in fieldset[1]:
                    fieldset_dict['extra'] = []
                    for info in fieldset[1]['extra']:
                        fieldset_dict['extra'].append(info)