コード例 #1
0
    def add_actions(self):
        export_url = self.request.get_full_path()
        list_csv = get_metadata(self.qs.model, 'list_csv')
        list_xls = get_metadata(self.qs.model, 'list_xls')
        log = get_metadata(self.qs.model, 'log')
        app_label = get_metadata(self.qs.model, 'app_label')
        list_pdf = get_metadata(self.qs.model, 'list_pdf')

        if list_csv:
            export_url = '?' in export_url and '{}&export=csv'.format(
                export_url) or '{}?export=csv'.format(export_url)
            self.add_action('Exportar CSV', export_url, 'ajax', 'fa-table')

        if list_xls:
            export_url = '?' in export_url and '{}&export=excel'.format(
                export_url) or '{}?export=excel'.format(export_url)
            self.add_action('Exportar Excel', export_url, 'ajax',
                            'fa-file-excel-o')

        if log:
            log_url = '/log/{}/{}/'.format(app_label,
                                           self.qs.model.__name__.lower())
            if self.request.user.has_perm('admin.list_log'):
                self.add_action('Visualizar Log', log_url, 'ajax',
                                'fa-history')

        if list_pdf:
            pdf_url = '?' in export_url and '{}&export=pdf'.format(
                export_url) or '{}?export=pdf'.format(export_url)
            self.add_action('Imprimir', pdf_url, 'ajax', 'fa-print')

        subclasses = self.qs.model.__subclasses__()

        if not subclasses and permissions.has_add_permission(
                self.request, self.qs.model):
            instance = self.qs.model()
            instance.user = self.request.user
            if not hasattr(instance, 'can_add') or instance.can_add():
                add_label = get_metadata(self.qs.model, 'add_label',
                                         'Cadastrar')
                self.add_action(
                    add_label,
                    '/add/{}/{}/'.format(app_label,
                                         self.qs.model.__name__.lower()),
                    'ajax', 'fa-plus')

        for subclass in subclasses:
            app = get_metadata(subclass, 'app_label')
            verbose_name = get_metadata(subclass, 'verbose_name')
            cls = subclass.__name__.lower()
            if permissions.has_add_permission(self.request, subclass):
                self.add_action(verbose_name, '/add/{}/{}/'.format(app, cls),
                                False, 'fa-plus')
コード例 #2
0
 def add(self,
         queryset,
         start_field,
         end_field=None,
         color='#ccc',
         action_names=[],
         as_initial_date=False):
     item = dict(queryset=dumps_qs_query(queryset),
                 start_field=start_field,
                 end_field=end_field,
                 color=color,
                 action_names=','.join(action_names))
     self.items.append(item)
     if as_initial_date:
         qs_initial_date = queryset.order_by(start_field).values_list(
             start_field, flat=True)
         if qs_initial_date.exists():
             self.set_initial_date(qs_initial_date[0])
     if queryset.model not in self.models and has_add_permission(
             self.request, queryset.model):
         label = get_metadata(queryset.model, 'verbose_name')
         app_label = get_metadata(queryset.model, 'app_label')
         model_name = queryset.model.__name__.lower()
         url = '/add/{}/{}/?{}='.format(app_label, model_name, start_field)
         link = dict(label=label, url=url)
         self.links.append(link)
         self.models.append(queryset.model)
コード例 #3
0
    def __init__(self, request):
        from djangoplus.cache import loader
        super(ShortcutPanel, self).__init__('shortcutpanel', request)
        self.items = []

        for model, add_shortcut in loader.icon_panel_models:

            if type(add_shortcut) == bool:
                add_model = add_shortcut
            else:
                if not type(add_shortcut) in (list, tuple):
                    add_shortcut = add_shortcut,
                add_model = request.user.in_group(*add_shortcut)

            if add_model or request.user.is_superuser:
                if permissions.has_add_permission(request, model):
                    self.add_model(model)
        for item in loader.views:
            if item['add_shortcut']:
                if permissions.check_group_or_permission(
                        request, item['can_view']):
                    self.add(item['icon'], item['verbose_name'], None,
                             item['url'], item['can_view'], item['style'])
コード例 #4
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
コード例 #5
0
    def load_actions(self, action_names=None):

        from djangoplus.cache import CACHE
        export_url = self.request.get_full_path()
        list_csv = get_metadata(self.qs.model, 'list_csv')
        list_xls = get_metadata(self.qs.model, 'list_xls')
        log = get_metadata(self.qs.model, 'log')
        app_label = get_metadata(self.qs.model, 'app_label')
        list_pdf = get_metadata(self.qs.model, 'list_pdf')
        self.action_names = action_names or []

        subset = self.subsets and list(self.subsets.keys())[0] or None
        subsetp = self.request.GET.get('tab{}'.format(
            self.request.GET.get('tid')))
        subset_name = subsetp or subset

        # class actions defined in the manager
        if self.qs.model in CACHE['CLASS_ACTIONS']:
            for group in CACHE['CLASS_ACTIONS'][self.qs.model]:
                for view_name in CACHE['CLASS_ACTIONS'][self.qs.model][group]:
                    _action = CACHE['CLASS_ACTIONS'][
                        self.qs.model][group][view_name]
                    action_verbose_name = _action['verbose_name']
                    action_inline = _action['inline']
                    action_subsets = _action['subsets']
                    action_can_execute = _action['can_execute']
                    action_category = _action['group']
                    action_expose = _action['expose']
                    action_style = _action['style'] or 'popup'
                    if 'popup' not in action_style:
                        action_style = '{} popup'.format(action_style)
                    if self.is_list_view or view_name in self.action_names:
                        add_action = should_add_action(action_inline,
                                                       action_subsets,
                                                       subset_name)
                        add_action = add_action and (True in action_expose
                                                     or 'web' in action_expose)
                        if add_action and permissions.check_group_or_permission(
                                self.request, action_can_execute):
                            func = getattr(self.qs, view_name)
                            ignore_pdf = False
                            if count_parameters_names(func) > 0:
                                action_style = action_style.replace('pdf', '')
                                ignore_pdf = True
                            char = '?' in self.request.get_full_path(
                            ) and '&' or '?'
                            url = '{}{}{}'.format(self.request.get_full_path(),
                                                  char,
                                                  '{}='.format(view_name))
                            self.add_action(action_verbose_name, url,
                                            action_style, None,
                                            action_category)
                            if view_name in self.request.GET:
                                self._proccess_request(func, _action,
                                                       ignore_pdf)

        # subset actions defined in the manager
        if self.qs.model in CACHE['QUERYSET_ACTIONS']:
            for group in CACHE['QUERYSET_ACTIONS'][self.qs.model]:
                for view_name in CACHE['QUERYSET_ACTIONS'][
                        self.qs.model][group]:
                    _action = CACHE['QUERYSET_ACTIONS'][
                        self.qs.model][group][view_name]
                    action_verbose_name = _action['verbose_name']
                    action_can_execute = _action['can_execute']
                    action_inline = _action['inline']
                    action_icon = _action['icon']
                    action_subsets = _action['subsets']
                    action_condition = _action['condition']
                    action_source = _action['source']
                    action_category = _action['group']
                    action_expose = _action['expose']
                    action_style = _action['style'] or 'popup'
                    if 'popup' not in action_style:
                        action_style = '{} popup'.format(action_style)
                    if view_name in self.action_names or (
                            self.is_list_view
                            and action_inline) or (self.current_tab
                                                   in action_subsets):
                        add_action = should_add_action(action_inline,
                                                       action_subsets,
                                                       subset_name)
                        add_action = add_action and (True in action_expose
                                                     or 'web' in action_expose)
                        if add_action and permissions.check_group_or_permission(
                                self.request, action_can_execute):
                            self.display_checkboxes = self.display_checkboxes or not action_source == 'view'
                            func = getattr(self.qs, view_name)
                            ignore_pdf = False
                            char = '?' in self.request.get_full_path(
                            ) and '&' or '?'
                            url = '{}{}{}'.format(self.request.get_full_path(),
                                                  char,
                                                  '{}='.format(view_name))
                            if count_parameters_names(func) > 0:
                                ignore_pdf = True
                                action_style = action_style.replace('pdf', '')
                            self.add_queryset_action(action_verbose_name, url,
                                                     action_style, action_icon,
                                                     action_category,
                                                     action_condition)

                            if view_name in self.request.GET:
                                ids = self.get_selected_ids()
                                if ids:
                                    qs = self.get_queryset(
                                        paginate=False).filter(id__in=ids)
                                else:
                                    break
                                func = getattr(qs, view_name)
                                self._proccess_request(func, _action,
                                                       ignore_pdf)

        # class actions defined in views module
        if self.qs.model in CACHE['CLASS_VIEW_ACTIONS']:
            for group in CACHE['CLASS_VIEW_ACTIONS'][self.qs.model]:
                for view_name in CACHE['CLASS_VIEW_ACTIONS'][
                        self.qs.model][group]:
                    _action = CACHE['CLASS_VIEW_ACTIONS'][
                        self.qs.model][group][view_name]
                    action_verbose_name = _action['verbose_name']
                    action_inline = _action['inline']
                    action_subsets = _action['subsets']
                    action_can_execute = _action['can_execute']
                    action_category = _action['group']
                    action_expose = _action['expose']
                    action_style = _action['style'] or 'popup'
                    url = '/{}/{}/'.format(
                        get_metadata(self.qs.model, 'app_label'), view_name)
                    action_style = action_style.replace('popup', '')
                    if self.is_list_view or view_name in self.action_names:
                        add_action = should_add_action(action_inline,
                                                       action_subsets,
                                                       subset_name)
                        add_action = add_action and (True in action_expose
                                                     or 'web' in action_expose)
                        if add_action and permissions.check_group_or_permission(
                                self.request, action_can_execute):
                            self.add_action(action_verbose_name, url,
                                            action_style, None,
                                            action_category)

        if self.is_list_view:
            # utility actions
            if list_csv:
                export_url = '?' in export_url and '{}&export=csv'.format(
                    export_url) or '{}?export=csv'.format(export_url)
                self.add_action('Exportar CSV', export_url, 'ajax', 'fa-table')

            if list_xls:
                export_url = '?' in export_url and '{}&export=excel'.format(
                    export_url) or '{}?export=excel'.format(export_url)
                self.add_action('Exportar Excel', export_url, 'ajax',
                                'fa-file-excel-o')

            if log:
                log_url = '/log/{}/{}/'.format(app_label,
                                               self.qs.model.__name__.lower())
                if self.request.user.has_perm('admin.list_log'):
                    self.add_action('Visualizar Log', log_url, 'ajax',
                                    'fa-history')

            if list_pdf:
                pdf_url = '?' in export_url and '{}&export=pdf'.format(
                    export_url) or '{}?export=pdf'.format(export_url)
                self.add_action('Imprimir', pdf_url, 'ajax', 'fa-print')

            # registration action
            subclasses = ()  #self.qs.model.__subclasses__()
            if not subclasses and not self.subsets and permissions.has_add_permission(
                    self.request, self.qs.model):
                instance = self.qs.model()
                instance._user = self.request.user
                if not hasattr(instance, 'can_add') or instance.can_add():
                    if self.relation:
                        verbose_name = get_metadata(self.qs.model,
                                                    'verbose_name')
                        add_label = get_metadata(
                            self.qs.model, 'add_label',
                            '{} {}'.format(_('Add'), verbose_name))
                    else:
                        add_label = get_metadata(self.qs.model, 'add_label',
                                                 _('Add'))
                    add_url = '/add/{}/{}/'.format(
                        app_label, self.qs.model.__name__.lower())
                    self.add_action(add_label, add_url, 'ajax', 'fa-plus')

            for subclass in subclasses:
                app = get_metadata(subclass, 'app_label')
                verbose_name = get_metadata(subclass, 'verbose_name')
                cls = subclass.__name__.lower()
                if permissions.has_add_permission(self.request, subclass):
                    self.add_action(verbose_name,
                                    '/add/{}/{}/'.format(app, cls), False,
                                    'fa-plus')
コード例 #6
0
ファイル: views.py プロジェクト: allysonbarros/djangoplus
def add(request, app, cls, pk=None, related_field_name=None, related_pk=None):

    if not request.user.is_authenticated:
        return httprr(request,
                      '/admin/login/?next={}'.format(request.get_full_path()))

    try:
        _model = apps.get_model(app, cls)
    except LookupError as e:
        return page_not_found(request, e, 'error404.html')

    obj = pk and _model.objects.all(
        request.user).filter(pk=pk).first() or _model()
    obj.request = request
    obj._user = request.user

    title = pk and str(obj) or get_metadata(_model, 'verbose_name')

    if related_field_name is None:

        if obj.pk:
            if not permissions.has_edit_permission(
                    request, _model) or not permissions.can_edit(request, obj):
                return HttpResponseForbidden()
        else:
            if not permissions.has_add_permission(
                    request, _model) or not permissions.can_add(request, obj):
                return HttpResponseForbidden()

        form = factory.get_register_form(request, obj)
        title = form.title

    elif is_one_to_many(_model, related_field_name):
        if not permissions.can_add(request, obj) and not permissions.can_edit(
                request, obj):
            return HttpResponseForbidden()
        form = factory.get_one_to_many_form(request, obj, related_field_name)

    elif is_many_to_many(_model, related_field_name):
        if not permissions.can_add(request, obj) and not permissions.can_edit(
                request, obj):
            return HttpResponseForbidden()
        form = factory.get_many_to_many_form(request, obj, related_field_name,
                                             related_pk)

    elif is_one_to_many_reverse(_model, related_field_name):
        form = factory.get_many_to_many_reverse_form(request, obj,
                                                     related_field_name)

    elif is_one_to_one(_model, related_field_name):
        if not permissions.can_add(request, obj) and not permissions.can_edit(
                request, obj):
            return HttpResponseForbidden()
        form = factory.get_one_to_one_form(request, obj, related_field_name,
                                           related_pk)
    else:
        # many to one
        for rel in list_related_objects(_model):
            if hasattr(rel, 'get_accessor_name'):
                if rel.get_accessor_name() in (
                        '{}_set'.format(related_field_name),
                        related_field_name):
                    related_queryset = rel.related_model.objects.all(
                        request.user)
                    related_obj = related_pk and related_queryset.get(
                        pk=related_pk) or rel.related_model()
                    related_obj.request = request
                    setattr(related_obj, rel.field.name, obj)
                    setattr(related_obj, '{}_id'.format(rel.field.name),
                            obj.pk)
                    if related_pk:
                        if not permissions.has_edit_permission(
                                request,
                                rel.related_model) or not permissions.can_edit(
                                    request, related_obj):
                            return HttpResponseForbidden()
                    else:
                        if not permissions.has_add_permission(
                                request,
                                rel.related_model) or not permissions.can_add(
                                    request, related_obj):
                            return HttpResponseForbidden()
                    form = factory.get_many_to_one_form(
                        request, obj, rel.get_accessor_name(), related_obj)
                    title = form.title

    if form.is_valid():
        is_editing = form.instance.pk is not None
        try:
            form.save()
            obj = form.instance
            if 'select' in request.GET:
                return HttpResponse('{}|{}|{}'.format(obj.pk, obj,
                                                      request.GET['select']))
            elif related_field_name:
                message = 'Ação realizada com sucesso'
                url = '..'
            else:
                message = get_metadata(form.instance.__class__, 'add_message')
                if message and not is_editing:
                    if hasattr(obj, 'get_absolute_url'):
                        url = obj.get_absolute_url()
                    else:
                        url = '/view/{}/{}/{}/'.format(
                            get_metadata(obj.__class__, 'app_label'),
                            obj.__class__.__name__.lower(), obj.pk)
                else:
                    url = '..'
                if is_editing:
                    message = message or 'Atualização realizada com sucesso'
                else:
                    message = message or 'Cadastro realizado com sucesso'
            return httprr(request, url, message)
        except ValidationError as e:
            form.add_error(None, str(e.message))
    return render(request, 'default.html', locals())
コード例 #7
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)