예제 #1
0
    def get_form_layout(self):
        layout = copy.deepcopy(self.detail_layout or self.form_layout)

        if layout is None:
            layout = Layout(Container(
                Fieldset("", *self.form_obj.fields.keys(), css_class="unsort no_title"), css_class="form-horizontal"
            ))
        elif type(layout) in (list, tuple) and len(layout) > 0:
            if isinstance(layout[0], Column):
                layout = Layout(Container(*layout))
            elif isinstance(layout[0], Fieldset):
                layout = Layout(
                    Container(*layout, css_class="form-horizontal"))
            else:
                layout = Layout(Container(Fieldset("", *layout, css_class="unsort no_title"), css_class="form-horizontal"))

            if self.detail_show_all:
                rendered_fields = [i[1] for i in layout.get_field_names()]
                container = layout[0].fields
                other_fieldset = Fieldset(_(u'Other Fields'), *[f for f in self.form_obj.fields.keys() if f not in rendered_fields])

                if len(other_fieldset.fields):
                    if len(container) and isinstance(container[0], Column):
                        container[0].fields.append(other_fieldset)
                    else:
                        container.append(other_fieldset)

        return layout
예제 #2
0
    def get_form_layout(self):
        layout = copy.deepcopy(self.form_layout)
        arr = self.form_obj.fields.keys()
        arr = [k for k in arr]
        fields = arr + list(self.get_readonly_fields())

        if layout is None:
            layout = Layout(Container(Col('full',
                                          Fieldset("", *fields, css_class="unsort no_title"), horizontal=True, span=12)
                                      ))
        elif type(layout) in (list, tuple) and len(layout) > 0:
            if isinstance(layout[0], Column):
                fs = layout
            elif isinstance(layout[0], (Fieldset, TabHolder)):
                fs = (Col('full', *layout, horizontal=True, span=12),)
            else:
                fs = (Col('full', Fieldset("", *layout, css_class="unsort no_title"), horizontal=True, span=12),)

            layout = Layout(Container(*fs))

            rendered_fields = [i[1] for i in layout.get_field_names()]
            container = layout[0].fields
            other_fieldset = Fieldset(_(u'Other Fields'), *[f for f in fields if f not in rendered_fields])

            if len(other_fieldset.fields):
                if len(container) and isinstance(container[0], Column):
                    container[0].fields.append(other_fieldset)
                else:
                    container.append(other_fieldset)

        return layout
예제 #3
0
 def get_form_layout(self):
     if self.request.user.is_superuser:
         self.form_layout = Layout(Container(Col('full',
                                                 Fieldset(
                                                     "", "title", "content", "user", css_class="unsort no_title"),
                                                 horizontal=True, span=12)
                                             ))
     else:
         self.form_layout = Layout(Container(Col('full',
                                                 Fieldset(
                                                     "", "title", "content", css_class="unsort no_title"),
                                                 horizontal=True, span=12)
                                             ))
     return super(ArticleAdmin, self).get_form_layout()
예제 #4
0
    def get_form_layout(self):
        """
        返回 Form Layout ,如果您设置了 :attr:`detail_layout` 属性,则使用 :attr:`form_layout` 属性,如果都没有该方法会自动生成 Form Layout 。
        有关 Form Layout 的更多信息可以参看 `Crispy Form 文档 <http://django-crispy-forms.readthedocs.org/en/latest/layouts.html>`_
        设置 Form Layout 可以非常灵活的显示页面的各个元素
        """
        # 复制避免修改属性值
        layout = copy.deepcopy(self.detail_layout or self.form_layout)

        if layout is None:
            layout = Layout(
                Container(
                    Col('full',
                        Fieldset("",
                                 *self.form_obj.fields.keys(),
                                 css_class="unsort no_title"),
                        horizontal=True,
                        span=12)))
        elif type(layout) in (list, tuple) and len(layout) > 0:
            # 如果设置的 layout 是一个列表,那么按以下方法生成
            if isinstance(layout[0], Column):
                fs = layout
            elif isinstance(layout[0], (Fieldset, TabHolder)):
                fs = (Col('full', *layout, horizontal=True, span=12), )
            else:
                fs = (Col('full',
                          Fieldset("", *layout, css_class="unsort no_title"),
                          horizontal=True,
                          span=12), )

            layout = Layout(Container(*fs))

            if self.detail_show_all:
                # 显示没有在 Layout 中出现的字段
                rendered_fields = [i[1] for i in layout.get_field_names()]
                container = layout[0].fields
                other_fieldset = Fieldset(
                    _(u'Other Fields'), *[
                        f for f in self.form_obj.fields.keys()
                        if f not in rendered_fields
                    ])

                if len(other_fieldset.fields):
                    if len(container) and isinstance(container[0], Column):
                        container[0].fields.append(other_fieldset)
                    else:
                        container.append(other_fieldset)

        return layout
예제 #5
0
파일: edit.py 프로젝트: ldsxp/xadmin-py3
    def get_form_layout(self):
        """
        返回 Form Layout ,如果您设置了 :attr:`form_layout` 属性,则使用该属性,否则该方法会自动生成 Form Layout 。
        有关 Form Layout 的更多信息可以参看 `Crispy Form 文档 <http://django-crispy-forms.readthedocs.org/en/latest/layouts.html>`_
        设置 Form Layout 可以非常灵活的显示表单页面的各个元素
        """
        layout = copy.deepcopy(self.form_layout)
        arr = self.form_obj.fields.keys()
        if six.PY3:
            arr = [k for k in arr]
        fields = arr + list(self.get_readonly_fields())

        if layout is None:
            layout = Layout(
                Container(
                    Col('full',
                        Fieldset("", *fields, css_class="unsort no_title"),
                        horizontal=True,
                        span=12)))
        elif type(layout) in (list, tuple) and len(layout) > 0:
            # 如果设置的 layout 是一个列表,那么按以下方法生成
            if isinstance(layout[0], Column):
                fs = layout
            elif isinstance(layout[0], (Fieldset, TabHolder)):
                fs = (Col('full', *layout, horizontal=True, span=12), )
            else:
                fs = (Col('full',
                          Fieldset("", *layout, css_class="unsort no_title"),
                          horizontal=True,
                          span=12), )

            layout = Layout(Container(*fs))

            rendered_fields = [i[1] for i in layout.get_field_names()]
            container = layout[0].fields
            other_fieldset = Fieldset(
                _(u'Other Fields'),
                *[f for f in fields if f not in rendered_fields])

            # 将所有没有显示的字段和在一个 Fieldset 里面显示
            if len(other_fieldset.fields):
                if len(container) and isinstance(container[0], Column):
                    # 把其他字段放在第一列显示
                    container[0].fields.append(other_fieldset)
                else:
                    container.append(other_fieldset)

        return layout
예제 #6
0
    def get_form_layout(self):
        layout = copy.deepcopy(self.detail_layout or self.form_layout)

        if layout is None:
            layout = Layout(
                Container(
                    Col(
                        "full",
                        Fieldset("",
                                 *self.form_obj.fields.keys(),
                                 css_class="unsort no_title"),
                        horizontal=True,
                        span=12,
                    )))
        elif type(layout) in (list, tuple) and len(layout) > 0:
            if isinstance(layout[0], Column):
                fs = layout
            elif isinstance(layout[0], (Fieldset, TabHolder)):
                fs = (Col("full", *layout, horizontal=True, span=12), )
            else:
                fs = (Col(
                    "full",
                    Fieldset("", *layout, css_class="unsort no_title"),
                    horizontal=True,
                    span=12,
                ), )

            layout = Layout(Container(*fs))

            if self.detail_show_all:
                rendered_fields = [i[1] for i in layout.get_field_names()]
                container = layout[0].fields
                other_fieldset = Fieldset(
                    _(u"Other Fields"), *[
                        f for f in self.form_obj.fields.keys()
                        if f not in rendered_fields
                    ])

                if len(other_fieldset.fields):
                    if len(container) and isinstance(container[0], Column):
                        container[0].fields.append(other_fieldset)
                    else:
                        container.append(other_fieldset)

        return layout
예제 #7
0
    def instance_form(self, **kwargs):
        formset = self.get_formset(**kwargs)
        attrs = {
            'instance': self.model_instance,
            'queryset': self.queryset()
        }
        if self.request_method == 'post':
            attrs.update({
                'data': self.request.POST, 'files': self.request.FILES,
                'save_as_new': "_saveasnew" in self.request.POST
            })
        instance = formset(**attrs)
        instance.view = self

        helper = FormHelper()
        helper.form_tag = False
        # override form method to prevent render csrf_token in inline forms, see template 'bootstrap/whole_uni_form.html'
        helper.form_method = 'get'

        style = style_manager.get_style(
            'one' if self.max_num == 1 else self.style)(self, instance)

        if len(instance):
            layout = copy.deepcopy(self.form_layout)

            if layout is None:
                layout = Layout(*instance[0].fields.keys())
            elif type(layout) in (list, tuple) and len(layout) > 0:
                layout = Layout(*layout)

                rendered_fields = [i[1] for i in layout.get_field_names()]
                layout.extend([f for f in instance[0]
                              .fields.keys() if f not in rendered_fields])

            helper.add_layout(layout)

            style.update_layout(helper)

            # replace delete field with Dynamic field, for hidden delete field when instance is NEW.
            helper[DELETION_FIELD_NAME].wrap(DeleteField)

        instance.helper = helper
        instance.style = style

        return instance
예제 #8
0
    def do_action(self, queryset):
        if not self.has_change_permission():
            raise PermissionDenied

        change_fields = [
            f for f in self.request.POST.getlist(BATCH_CHECKBOX_NAME)
            if f in self.batch_fields
        ]

        if change_fields and self.request.POST.get("post"):
            self.form_obj = self.get_change_form(True, change_fields)(
                data=self.request.POST, files=self.request.FILES)
            if self.form_obj.is_valid():
                self.change_models(queryset, self.form_obj.cleaned_data)
                return None
        else:
            self.form_obj = self.get_change_form(False, self.batch_fields)()

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        helper.add_layout(
            Layout(
                Container(
                    Col(
                        "full",
                        Fieldset("",
                                 *self.form_obj.fields.keys(),
                                 css_class="unsort no_title"),
                        horizontal=True,
                        span=12,
                    ))))
        self.form_obj.helper = helper
        count = len(queryset)
        if count == 1:
            objects_name = force_text(self.opts.verbose_name)
        else:
            objects_name = force_text(self.opts.verbose_name_plural)

        context = self.get_context()
        context.update({
            "title": _("Batch change %s") % objects_name,
            "objects_name": objects_name,
            "form": self.form_obj,
            "queryset": queryset,
            "count": count,
            "opts": self.opts,
            "app_label": self.app_label,
            "action_checkbox_name": ACTION_CHECKBOX_NAME,
        })

        return TemplateResponse(
            self.request,
            self.batch_change_form_template
            or self.get_template_list("views/batch_change_form.html"),
            context,
        )
예제 #9
0
    def do_action(self, queryset):
        if not self.has_change_permission():
            raise PermissionDenied

        change_fields = [
            f for f in self.request.POST.getlist(BATCH_CHECKBOX_NAME)
            if f in self.batch_fields
        ]

        if change_fields and self.request.POST.get('post'):
            self.form_obj = self.get_change_form(True, change_fields)(
                data=self.request.POST, files=self.request.FILES)
            if self.form_obj.is_valid():
                self.change_models(queryset, self.form_obj.cleaned_data)
                return None
        else:
            self.form_obj = self.get_change_form(False, self.batch_fields)()

        helper = FormHelper()
        helper.form_tag = False
        helper.add_layout(
            Layout(
                Container(
                    Col('full',
                        Fieldset("",
                                 *list(self.form_obj.fields.keys()),
                                 css_class="unsort no_title"),
                        horizontal=True,
                        span=12))))
        self.form_obj.helper = helper
        count = len(queryset)
        if count == 1:
            objects_name = self.opts.verbose_name
        else:
            objects_name = self.opts.verbose_name_plural

        context = self.get_context()
        context.update({
            "title": _("Batch change %s") % objects_name,
            'objects_name': objects_name,
            'form': self.form_obj,
            'queryset': queryset,
            'count': count,
            "opts": self.opts,
            "app_label": self.app_label,
            'action_checkbox_name': ACTION_CHECKBOX_NAME,
        })

        return TemplateResponse(
            self.request,
            self.batch_change_form_template
            or self.get_template_list('views/batch_change_form.html'),
            context,
            current_app=self.admin_site.name)
예제 #10
0
    def do_action(self, queryset):
        if not self.has_change_permission():
            raise PermissionDenied

        form_class = self.get_change_form()

        if self.request.POST.get('post'):
            self.form_obj = form_class(data=self.request.POST,
                                       files=self.request.FILES)

            return None
        else:
            self.form_obj = form_class()

        helper = FormHelper()
        helper.form_tag = False  # 默认不需要 crispy 生成 form_tag
        helper.add_layout(
            Layout(
                Container(Fieldset("",
                                   *self.form_obj.fields.keys(),
                                   css_class="unsort no_title"),
                          css_class="form-horizontal")))
        self.form_obj.helper = helper

        if len(queryset) == 1:
            objects_name = force_unicode(self.opts.verbose_name)
        else:
            objects_name = force_unicode(self.opts.verbose_name_plural)

        context = self.get_context()
        context.update({
            "title": _("Change %s") % objects_name,
            'form': self.form_obj,
            'queryset': queryset,
            "opts": self.opts,
            "app_label": self.app_label,
            'action_checkbox_name': ACTION_CHECKBOX_NAME,
        })

        return TemplateResponse(
            self.request,
            self.batch_change_form_template
            or self.get_template_list('views/batch_change_form.html'),
            context,
            current_app=self.admin_site.name)
예제 #11
0
 def update_layout(self, helper):
     helper.add_layout(
         Layout(*[TDField(f) for f in self.formset[0].fields.keys()]))
예제 #12
0
    def instance_form(self, **kwargs):
        formset = self.get_formset(**kwargs)
        attrs = {
            'instance': self.model_instance,
            'queryset': self.queryset()
        }
        if self.request_method == 'post':
            attrs.update({
                'data': self.request.POST, 'files': self.request.FILES,
                'save_as_new': "_saveasnew" in self.request.POST
            })
        instance = formset(**attrs)
        instance.view = self

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        # override form method to prevent render csrf_token in inline forms, see templates 'bootstrap/whole_uni_form.html'
        helper.form_method = 'get'

        style = style_manager.get_style(
            'one' if self.max_num == 1 else self.style)(self, instance)
        style.name = self.style

        if len(instance):
            layout = copy.deepcopy(self.form_layout)

            if layout is None:
                layout = Layout(*instance[0].fields.keys())
            elif type(layout) in (list, tuple) and len(layout) > 0:
                layout = Layout(*layout)

                rendered_fields = [i[1] for i in layout.get_field_names()]
                layout.extend([f for f in instance[0]
                               .fields.keys() if f not in rendered_fields])

            helper.add_layout(layout)
            style.update_layout(helper)

            # replace delete field with Dynamic field, for hidden delete field when instance is NEW.
            helper[DELETION_FIELD_NAME].wrap(DeleteField)

        instance.helper = helper
        instance.style = style

        readonly_fields = self.get_readonly_fields()
        if readonly_fields:
            for form in instance:
                form.readonly_fields = []
                inst = form.save(commit=False)
                if inst:
                    meta_field_names = [field.name for field in inst._meta.get_fields()]
                    for readonly_field in readonly_fields:
                        value = None
                        label = None
                        if readonly_field in meta_field_names:
                            label = inst._meta.get_field(readonly_field).verbose_name
                            value = smart_text(getattr(inst, readonly_field))
                        elif inspect.ismethod(getattr(inst, readonly_field, None)):
                            value = getattr(inst, readonly_field)()
                            label = getattr(getattr(inst, readonly_field), 'short_description', readonly_field)
                        elif inspect.ismethod(getattr(self, readonly_field, None)):
                            value = getattr(self, readonly_field)(inst)
                            label = getattr(getattr(self, readonly_field), 'short_description', readonly_field)
                        if value:
                            form.readonly_fields.append({'label': label, 'contents': value})
        return instance
예제 #13
0
 def get_form_layout(self, __):
     if '_field' in self.request.GET:
         return Layout(*self.request.GET['_field'].split(','))
     return __()
예제 #14
0
 def get_form_layout(self, __):
     if "_field" in self.request.GET:
         return Layout(*self.request.GET["_field"].split(","))
     return __()