Пример #1
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)
        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:
                    for readonly_field in readonly_fields:
                        value = None
                        label = None
                        if readonly_field in inst._meta.get_all_field_names():
                            label = inst._meta.get_field_by_name(readonly_field)[0].verbose_name
                            value = unicode(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)
                        if value:
                            form.readonly_fields.append({"label": label, "contents": value})
        return instance
Пример #2
0
    def get_form_helper(self):
        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        helper.add_layout(self.get_form_layout())

        return helper
Пример #3
0
 def get_form_helper(self):
     helper = FormHelper()
     helper.form_tag = False
     helper.include_media = False
     layout = self.get_form_layout()
     replace_field_to_value(layout, self.get_field_result)
     helper.add_layout(layout)
     return helper
Пример #4
0
    def setup(self):
        helper = FormHelper()
        helper.form_tag = False
        self.helper = helper

        self.id = self.cleaned_data['id']
        self.title = self.cleaned_data['title'] or self.base_title

        if not (self.user.is_superuser or self.has_perm()):
            raise PermissionDenied
Пример #5
0
    def context(self, context):
        helper = FormHelper()
        helper.form_tag = False

        context.update({
            'addform': self.add_view.form_obj,
            'addhelper': helper,
            'addurl': self.add_view.model_admin_url('add'),
            'model': self.model
        })
Пример #6
0
    def context(self, context):
        helper = FormHelper()
        helper.form_tag = False

        context.update(
            {
                "addform": self.add_view.form_obj,
                "addhelper": helper,
                "addurl": self.add_view.model_admin_url("add"),
                "model": self.model,
            }
        )
Пример #7
0
    def get_form_helper(self):
        helper = FormHelper()
        helper.form_tag = False
        helper.add_layout(self.get_form_layout())

        # deal with readonly fields
        readonly_fields = self.get_readonly_fields()
        if readonly_fields:
            detail = self.get_model_view(DetailAdminUtil, self.model, self.form_obj.instance)
            for field in readonly_fields:
                helper[field].wrap(ReadOnlyField, detail)
                
        return helper
Пример #8
0
 def get_context(self):
     context = super(ChangePasswordView, self).get_context()
     helper = FormHelper()
     helper.form_tag = False
     self.form.helper = helper
     context.update({
         'title': _('Change password: %s') % escape(unicode(self.obj)),
         'form': self.form,
         'has_delete_permission': False,
         'has_change_permission': True,
         'has_view_permission': True,
         'original': self.obj,
     })
     return context
Пример #9
0
 def get_context(self):
     context = super(ChangePasswordView, self).get_context()
     helper = FormHelper()
     helper.form_tag = False
     self.form.helper = helper
     context.update(
         {
             "title": _("Change password: %s") % escape(str(self.obj)),
             "form": self.form,
             "has_delete_permission": False,
             "has_change_permission": True,
             "has_view_permission": True,
             "original": self.obj,
         }
     )
     return context
Пример #10
0
 def get(self, request, *args, **kwargs):
     context = self.get_context()
     helper = FormHelper()
     helper.form_tag = False
     context.update({
         'title': self.title,
         'helper': helper,
         'app_path': request.get_full_path(),
         REDIRECT_FIELD_NAME: request.get_full_path(),
     })
     defaults = {
         'extra_context': context,
         'current_app': self.admin_site.name,
         'authentication_form': self.login_form or AdminAuthenticationForm,
         'template_name': self.login_template or 'xadmin/views/login.html',
     }
     self.update_params(defaults)
     return login(request, **defaults)
Пример #11
0
    def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET["fields"].split(",") if f in model_fields]
        defaults = {"form": self.form, "fields": fields, "formfield_callback": self.formfield_for_dbfield}
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        form.helper = helper

        s = (
            '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}'
            + '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        )
        t = template.Template(s)
        c = template.Context({"form": form, "action_url": self.model_admin_url("patch", self.org_obj.pk)})

        return HttpResponse(t.render(c))
Пример #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
        # 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
Пример #13
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)
Пример #14
0
    def get_form_helper(self):
        """
        取得 Crispy Form 需要的 FormHelper。具体信息可以参看 `Crispy Form 文档 <http://django-crispy-forms.readthedocs.org/en/latest/tags.html#crispy-tag>`_ 
        """
        helper = FormHelper()
        helper.form_tag = False # 默认不需要 crispy 生成 form_tag
        helper.add_layout(self.get_form_layout())

        # 处理只读字段
        readonly_fields = self.get_readonly_fields()
        if readonly_fields:
            # 使用 :class:`xadmin.views.detail.DetailAdminUtil` 来显示只读字段的内容
            detail = self.get_model_view(
                DetailAdminUtil, self.model, self.form_obj.instance)
            for field in readonly_fields:
                # 替换只读字段
                helper[field].wrap(ReadOnlyField, detail=detail)


        return helper
Пример #15
0
 def get_form_helper(self):
     helper = FormHelper()
     helper.form_tag = False
     helper.include_media = False
     layout = self.get_form_layout()
     replace_field_to_value(layout, self.get_field_result)
     helper.add_layout(layout)
     helper.filter(
         basestring, max_level=20).wrap(ShowField, admin_view=self)
     return helper
Пример #16
0
    def get_form_helper(self):
        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        helper.add_layout(self.get_form_layout())
        helper.field_template = "xadmin/layout/field.html"

        return helper
Пример #17
0
    def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% csrf_token %}{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
#         c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})
        c = template.RequestContext(request, {'form': form, 'action_url': self.request.get_full_path()})

        return HttpResponse(t.render(c))
Пример #18
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('batch_change_form.html'), context, current_app=self.admin_site.name)
Пример #19
0
    def get(self, request, *args, **kwargs):
        context = self.get_context()
        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
                
        if request.get_full_path() == self.get_admin_url('login'):
            next_url = self.get_admin_url('index')
        else:
            next_url = request.get_full_path()

        context.update({
            'title': self.title,
            'helper': helper,
            'app_path': request.get_full_path(),
            'site_title': self.site_title,
            'site_footer': self.site_footer,
            REDIRECT_FIELD_NAME: next_url,
        })
        defaults = {
            'extra_context': context,
            'current_app': self.admin_site.name,
            'authentication_form': self.login_form or AdminAuthenticationForm,
            'template_name': self.login_template or 'xadmin/views/login.html',
        }
        self.update_params(defaults)
        
        if getattr(settings, 'GOOGLE_RECAPTCHA_SITE_ID', ''):
            context['GOOGLE_RECAPTCHA_SITE_ID'] = settings.GOOGLE_RECAPTCHA_SITE_ID

            if request.method == 'POST' and getattr(settings, 'GOOGLE_RECAPTCHA_SECRET_KEY', '') and not request.recaptcha_is_valid:
                # reCaptcha fail
                context.update({'recaptcha_message': _(u'Please check the above verify box!')})
                return render(request, defaults['template_name'], context)

        return login(request, **defaults)
Пример #20
0
 def get_form_helper(self):
     """
     取得 Crispy Form 需要的 FormHelper。具体信息可以参看 `Crispy Form 文档 <http://django-crispy-forms.readthedocs.org/en/latest/tags.html#crispy-tag>`_ 
     """
     helper = FormHelper()
     helper.form_tag = False
     layout = self.get_form_layout()
     # 替换所有的字段为 ShowField
     replace_field_to_value(layout, self.get_field_result)
     helper.add_layout(layout)
     helper.filter(
         basestring, max_level=20).wrap(ShowField, admin_view=self)
     return helper
Пример #21
0
    def get_form_helper(self):
        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        helper.add_layout(self.get_form_layout())

        # deal with readonly fields
        readonly_fields = self.get_readonly_fields()
        if readonly_fields:
            detail = self.get_model_view(DetailAdminUtil, self.model,
                                         self.form_obj.instance)
            for field in readonly_fields:
                helper[field].wrap(ReadOnlyField, detail=detail)

        return helper
Пример #22
0
    def do_action(self, queryset):
        if self.has_change_permission():
            pass
        else:
            for obj in queryset:
                if not self.has_change_permission_obj(obj):
                    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)
Пример #23
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
Пример #24
0
    def get_form_helper(self):
        """
        取得 Crispy Form 需要的 FormHelper。具体信息可以参看 `Crispy Form 文档 <http://django-crispy-forms.readthedocs.org/en/latest/tags.html#crispy-tag>`_ 
        """
        helper = FormHelper()
        helper.form_tag = False  # 默认不需要 crispy 生成 form_tag
        helper.include_media = False
        helper.add_layout(self.get_form_layout())

        # 处理只读字段
        readonly_fields = self.get_readonly_fields()
        if readonly_fields:
            # 使用 :class:`xadmin.views.detail.DetailAdminUtil` 来显示只读字段的内容
            detail = self.get_model_view(DetailAdminUtil, self.model,
                                         self.form_obj.instance)
            for field in readonly_fields:
                # 替换只读字段
                helper[field].wrap(ReadOnlyField, detail=detail)

        return helper
Пример #25
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
Пример #26
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 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)
        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
Пример #27
0
    def get_form_helper(self):
        helper = FormHelper()
        helper.form_tag = False
        helper.add_layout(self.get_form_layout())

        return helper