Esempio n. 1
0
 def __init__(self, request, scope=None, organization=None, unit=None, *args, **kwargs):
     super(LoginForm, self).__init__(request, *args, **kwargs)
     self.scope = None
     self.fields['username'].widget.attrs['class'] = 'input-sm bounceIn animation-delay2'
     if scope:
         if scope == LoginForm.ORGANIZATION or scope == (
                 loader.organization_model and loader.organization_model.__name__.lower()):
             if organization:
                 self.scope_display = organization
             else:
                 organizations = Organization.objects.all()
                 self.fields['login_scope'] = forms.ModelChoiceField(organizations)
             self.scope = LoginForm.ORGANIZATION
         elif scope == LoginForm.UNIT or scope == (loader.unit_model and loader.unit_model.__name__.lower()):
             if unit:
                 self.scope_display = unit
             else:
                 if organization:
                     self.scope_display = organization
                     units = organization.get_units()
                 else:
                     units = Unit.objects.all()
                 self.fields['login_scope'] = forms.ModelChoiceField(units)
             self.scope = LoginForm.UNIT
     self.organization = organization
     self.unit = unit
Esempio n. 2
0
    def get_filter_form(self):
        form = forms.Form(self.request)
        form.title = 'Filtros'
        form.icon = 'fa-filter'
        form.partial = True
        self.filters = []
        for list_filter in self.get_list_filter():
            if type(list_filter) in (tuple, list):
                field_names = list_filter
            else:
                field_names = list_filter,
            for field_name in field_names:
                if self.relation and field_name == self.relation.hidden_field_name:
                    continue
                field = get_field(self.qs.model, field_name)
                form_field_name = '{}{}'.format(field_name, self.id)
                if hasattr(field, 'auto_now'):
                    initial = (self._get_from_request(field_name, None, '_0'), self._get_from_request(field_name, None, '_1'))
                    form.fields[form_field_name] = forms.DateFilterField(label=normalyze(field.verbose_name), initial=initial, required=False)
                else:
                    initial = self._get_from_request(field_name)
                    if type(field).__name__ in ['BooleanField', 'NullBooleanField']:
                        form.fields[form_field_name] = forms.ChoiceField(
                            choices=[['', ''], ['sim', 'Sim'], ['nao', 'Não'], ], label=normalyze(field.verbose_name), initial=initial, required=False)
                    elif hasattr(field, 'choices') and field.choices:
                        form.fields[form_field_name] = forms.ChoiceField(choices=[['', '']] + field.choices, label=normalyze(field.verbose_name), initial=initial, required=False)
                    else:
                        if hasattr(field.remote_field.model, 'unit_ptr_id') and self.request.user.role_set.filter(scope__unit__isnull=False).values_list('scope__unit', flat=True).count() == 1:
                            continue
                        if hasattr(field.remote_field.model, 'organization_ptr_id') and self.request.user.role_set.filter(scope__organization__isnull=False).values_list('scope__organization', flat=True).count() == 1:
                            continue
                        if field.remote_field and not should_filter_or_display(self.request, self.qs.model, field.remote_field.model):
                            continue
                        if initial:
                            if self.original_qs.query.can_filter():
                                pks = self.original_qs.order_by(field_name).values_list(field_name, flat=True).distinct()
                            else:
                                pks = self.original_qs.model.objects.all().order_by(field_name).values_list(field_name, flat=True).distinct()
                            qs = field.remote_field.model.objects.get_queryset().filter(pk__in=pks)
                            qs = qs | field.remote_field.model.objects.get_queryset().filter(pk=initial)
                        else:
                            if self.qs.query.can_filter():
                                pks = self.qs.order_by(field_name).values_list(field_name, flat=True).distinct()
                            else:
                                pks = self.qs.model.objects.all().order_by(field_name).values_list(field_name, flat=True).distinct()
                            qs = field.remote_field.model.objects.get_queryset().filter(pk__in=pks)
                        empty_label = ''

                        form.fields[form_field_name] = forms.ModelChoiceField(qs, label=normalyze(field.verbose_name), initial=initial, empty_label=empty_label, required=False, lazy=True, ignore_lookup=True, minimum_input_length=0)
                    form.fields[form_field_name].widget.attrs['data-placeholder'] = field.verbose_name
                    if initial:
                        label = form.fields[form_field_name].label
                        value = form.fields[form_field_name].clean(initial)
                        if type(form.fields[form_field_name]) == forms.ChoiceField:
                            for x, y in form.fields[form_field_name].choices:
                                if str(x) == str(value):
                                    value = y
                                    break
                        self.filters.append((label, value))
        return form
Esempio n. 3
0
    def __init__(self, request, title, qs, list_display=(), list_filter=()):
        super(ModelReport, self).__init__(request)
        self.title = title
        self.qs = qs
        self.components = []

        if list_filter:
            form = forms.Form(request)
            form.icon = 'fa-file-text-o'
            form.title = u''
            form.submit_label = u'Gerar Relatório'
            for field_name in list_filter:
                field = get_field(qs.model, field_name)
                form.fields[field_name] = forms.ModelChoiceField(
                    field.rel.to.objects.all(),
                    label=field.verbose_name,
                    required=False)
            if form.is_valid():
                for field_name in list_filter:
                    value = form.cleaned_data[field_name]
                    if value:
                        qs = qs.filter(**{field_name: value})
            self.form = form

        order_by = get_metadata(qs.model, 'order_by', iterable=True)
        if order_by:
            qs = qs.order_by(*order_by)
        table_description = get_metadata(qs.model, 'verbose_name_plural')
        self.table = ModelTable(request, table_description, qs, list_display)
Esempio n. 4
0
    def __init__(self,
                 request,
                 title,
                 qs,
                 list_display=(),
                 list_filter=(),
                 distinct=False):
        super(ModelReport, self).__init__(title, request)
        self.title = title
        self.qs = qs
        self.components = []
        self.filters = []

        if list_filter:
            form = forms.Form(request, method='GET')
            form.icon = 'fa-file-text-o'
            form.title = ''
            form.submit_label = 'Gerar Relatório'
            for field_name in list_filter:
                field = get_field(qs.model, field_name)
                if hasattr(field, 'choices') and field.choices:
                    form.fields[field_name] = forms.ChoiceField(
                        choices=[['', '']] + field.choices,
                        label=field.verbose_name,
                        required=False)
                else:
                    form.fields[field_name] = forms.ModelChoiceField(
                        field.remote_field.model.objects.all(),
                        label=field.verbose_name,
                        required=False)
            if form.is_valid():
                for field_name in list_filter:
                    value = form.cleaned_data[field_name]
                    if value:
                        qs = qs.filter(**{field_name: value})
                        self.filters.append(
                            (form.fields[field_name].label, value))
            self.form = form
        if distinct:
            pks = qs.values_list('pk', flat=True).order_by('pk').distinct()
            qs = qs.model.objects.filter(pk__in=pks)

        order_by = get_metadata(qs.model, 'order_by', iterable=True)
        if order_by:
            qs = qs.order_by(*order_by)
        table_description = get_metadata(qs.model, 'verbose_name_plural')
        self.table = ModelTable(request, table_description, qs, list_display)
Esempio n. 5
0
    def get_filter_form(self):
        form = forms.Form(self.request)
        form.title = 'Filtros'
        form.icon = 'fa-filter'
        form.partial = True
        self.filters = []
        for list_filter in self.get_list_filter():
            if type(list_filter) in (tuple, list):
                field_names = list_filter
            else:
                field_names = list_filter,
            for field_name in field_names:
                if field_name == self.to:
                    continue
                field = get_field(self.qs.model, field_name)
                form_field_name = '%s%s' % (field_name, self.id)
                if type(field).__name__ in ['DateField', 'DateTimeField']:
                    initial = (self._get_from_request(field_name, None, '_0'),
                               self._get_from_request(field_name, None, '_1'))
                    form.fields[form_field_name] = forms.DateFilterField(
                        label=normalyze(field.verbose_name),
                        initial=initial,
                        required=False)
                else:
                    initial = self._get_from_request(field_name)
                    if type(field).__name__ in [
                            'BooleanField', 'NullBooleanField'
                    ]:
                        form.fields[form_field_name] = forms.ChoiceField(
                            choices=[
                                ['', ''],
                                ['sim', 'Sim'],
                                ['nao', 'Não'],
                            ],
                            label=normalyze(field.verbose_name),
                            initial=initial,
                            required=False)
                    elif hasattr(field, 'choices') and field.choices:
                        form.fields[form_field_name] = forms.ChoiceField(
                            choices=[['', '']] + field.choices,
                            label=normalyze(field.verbose_name),
                            initial=initial,
                            required=False)
                    else:
                        if self.request.user.unit_id and hasattr(
                                field.rel.to, 'unit_ptr_id'):
                            continue
                        if self.request.user.organization_id and hasattr(
                                field.rel.to, 'organization_ptr_id'):
                            continue
                        if not should_filter_or_display(
                                self.request, self.qs.model, field.rel.to):
                            continue

                        if self.original_qs.query.can_filter():
                            pks = self.original_qs.order_by(
                                field_name).values_list(field_name,
                                                        flat=True).distinct()
                        else:
                            pks = self.original_qs.model.objects.all(
                            ).order_by(field_name).values_list(
                                field_name, flat=True).distinct()
                        qs = field.rel.to.objects.get_queryset().filter(
                            pk__in=pks)
                        empty_label = ''

                        form.fields[form_field_name] = forms.ModelChoiceField(
                            qs,
                            label=normalyze(field.verbose_name),
                            initial=initial,
                            empty_label=empty_label,
                            required=False)
                    form.fields[form_field_name].widget.attrs[
                        'data-placeholder'] = field.verbose_name
                    if initial:
                        label = form.fields[form_field_name].label
                        value = form.fields[form_field_name].clean(initial)
                        if type(form.fields[form_field_name]
                                ) == forms.ChoiceField:
                            for x, y in form.fields[form_field_name].choices:
                                if unicode(x) == unicode(value):
                                    value = y
                                    break
                        self.filters.append((label, value))
        return form
Esempio n. 6
0
def get_action_form(request, obj, action):
    action_function = action['function']
    action_verbose_name = action['verbose_name']
    initial = action['initial']
    action_input = action['input']
    action_choices = action['choices']
    action_display = action['display']
    app_label = get_metadata(type(obj), 'app_label')
    func = getattr(obj, action_function.__name__, action_function)

    if initial and hasattr(obj, initial):
        initial = getattr(obj, initial)()
    else:
        initial = {}
    if action_choices and hasattr(obj, action_choices):
        action_choices = getattr(obj, action_choices)()
    else:
        action_choices = {}

    if action_input:
        # it is a form name
        if type(action_input) in [str, str] and '.' not in action_input:
            full_app_name = settings.APP_MAPPING.get(app_label, app_label)
            fromlist = app_label
            module = __import__('{}.forms'.format(full_app_name),
                                fromlist=list(map(str, [app_label])))
            form_cls = getattr(module, action_input)

        # it is a model or model name
        else:
            if type(action_input) in [str, str]:
                app_name, class_name = action_input.split('.')
                action_input = apps.get_model(app_name, class_name)

            class Form(forms.ModelForm):
                class Meta:
                    model = action_input
                    fields = get_parameters_names(func)
                    title = action_verbose_name
                    submit_label = action_verbose_name

            form_cls = Form
    else:

        class Form(forms.ModelForm):
            class Meta:
                model = func.__self__.__class__
                fields = get_parameters_names(func)
                title = action_verbose_name
                submit_label = action_verbose_name

        form_cls = Form

    if issubclass(form_cls, forms.ModelForm):
        for key in list(initial.keys()):
            if hasattr(obj, key) and obj.pk and getattr(obj, key):
                del (initial[key])
        form = form_cls(request, instance=obj, initial=initial)
    else:
        form = form_cls(request, initial=initial)

    if action_display:
        for lookup in action_display:
            label = get_fiendly_name(func.__self__.__class__, lookup)
            value = getattr2(obj, lookup)
            form.fields[lookup] = forms.CharField(
                label=label,
                initial=value,
                required=False,
                widget=forms.widgets.DisplayInput(value))

    if action_choices:
        for field_name in action_choices:
            form.fields[field_name].queryset = action_choices[field_name]

    if not obj.pk:
        verbose_name = get_metadata(obj.__class__, 'verbose_name')
        form.fields['instance'] = forms.ModelChoiceField(
            type(obj).objects.all(), label=verbose_name)
        if form.fieldsets:
            form.fieldsets = ((verbose_name, {
                'fields': ('instance', )
            }), ) + form.fieldsets

    return form
Esempio n. 7
0
def get_action_form(request, obj, action):
    action_function = action['function']
    action_title = action['title']
    initial = action['initial']
    action_input = action['input']
    action_choices = action['choices']
    app_label = get_metadata(type(obj), 'app_label')
    func = getattr(obj, action_function.func_name, action_function)

    if initial and hasattr(obj, initial):
        initial = getattr(obj, initial)()
    else:
        initial = {}
    if action_choices and hasattr(obj, action_choices):
        action_choices = getattr(obj, action_choices)()
    else:
        action_choices = {}

    if action_input:
        # it is a form name
        if type(action_input) in [str, unicode] and '.' not in action_input:
            full_app_name = settings.APP_MAPPING.get(app_label, app_label)
            fromlist = app_label
            module = __import__('%s.forms' % full_app_name,
                                fromlist=[app_label])
            form_cls = getattr(module, action_input)

        # it is a model or model name
        else:
            if type(action_input) in [str, unicode]:
                app_name, class_name = action_input.split('.')
                action_input = apps.get_model(app_name, class_name)

            class Form(forms.ModelForm):
                class Meta:
                    model = action_input
                    fields = func.func_code.co_varnames[1:func.func_code.
                                                        co_argcount]
                    title = action_title
                    submit_label = action_title

            form_cls = Form
    else:

        class Form(forms.ModelForm):
            class Meta:
                model = func.im_class
                fields = func.func_code.co_varnames[1:func.func_code.
                                                    co_argcount]
                title = action_title
                submit_label = action_title

        form_cls = Form

    if issubclass(form_cls, forms.ModelForm):
        for key in initial.keys():
            if hasattr(obj, key) and obj.pk and getattr(obj, key):
                del (initial[key])
        form = form_cls(request, instance=obj, initial=initial)
    else:
        form = form_cls(request, initial=initial)

    if action_choices:
        for field_name in action_choices:
            form.fields[field_name].queryset = action_choices[field_name]

    if not obj.pk:
        verbose_name = get_metadata(obj.__class__, 'verbose_name')
        form.fields['instance'] = forms.ModelChoiceField(
            type(obj).objects.all(), label=verbose_name)
        if form.fieldsets:
            form.fieldsets = ((verbose_name, {
                'fields': ('instance', )
            }), ) + form.fieldsets

    return form