Esempio n. 1
0
    def _hack_inline_formset_initial(self, revision_view, formset):
        """Hacks the given formset to contain the correct initial data."""
        # Now we hack it to push in the data from the revision!
        initial = []
        related_versions = self.get_related_versions(revision_view.org_obj,
                                                     revision_view.version,
                                                     formset)
        formset.related_versions = related_versions
        for related_obj in formset.queryset:
            if unicode(related_obj.pk) in related_versions:
                initial.append(
                    related_versions.pop(unicode(related_obj.pk)).field_dict)
            else:
                initial_data = model_to_dict(related_obj)
                initial_data["DELETE"] = True
                initial.append(initial_data)
        for related_version in related_versions.values():
            initial_row = related_version.field_dict
            pk_name = ContentType.objects.get_for_id(
                related_version.content_type_id).model_class()._meta.pk.name
            del initial_row[pk_name]
            initial.append(initial_row)
        # Reconstruct the forms with the new revision data.
        formset.initial = initial
        formset.forms = [
            formset._construct_form(n) for n in xrange(len(initial))
        ]

        # Hack the formset to force a save of everything.

        def get_changed_data(form):
            return [field.name for field in form.fields]

        for form in formset.forms:
            form.has_changed = lambda: True
            form._get_changed_data = partial(get_changed_data, form=form)

        def total_form_count_hack(count):
            return lambda: count

        formset.total_form_count = total_form_count_hack(len(initial))

        if self.request.method == 'GET' and formset.helper and formset.helper.layout:
            helper = formset.helper
            helper.filter(dutils.basestring).wrap(InlineDiffField)
            fake_admin_class = type(
                str('%s%sFakeAdmin' %
                    (self.opts.app_label, self.opts.module_name)), (object, ),
                {'model': self.model})
            for form in formset.forms:
                instance = form.instance
                if instance.pk:
                    form.detail = self.get_view(DetailAdminUtil,
                                                fake_admin_class, instance)
Esempio n. 2
0
 def post_response(self):
     self.message_user(
         _('The %(model)s "%(name)s" was recovered successfully. You may edit it again below.'
           ) % {
               "model": force_unicode(self.opts.verbose_name),
               "name": unicode(self.new_obj)
           }, 'success')
     return HttpResponseRedirect(
         self.model_admin_url('change', self.new_obj.pk))
Esempio n. 3
0
    def init_request(self, object_id, version_id):
        self.detail = self.get_model_view(DetailAdminView, self.model,
                                          object_id)
        self.org_obj = self.detail.obj
        self.version = get_object_or_404(Version,
                                         pk=version_id,
                                         object_id=unicode(self.org_obj.pk))

        self.prepare_form()
Esempio n. 4
0
 def get_related_versions(self, obj, version, formset):
     """Retreives all the related Version objects for the given FormSet."""
     object_id = obj.pk
     # Get the fk name.
     try:
         fk_name = formset.fk.name
     except AttributeError:
         # This is a GenericInlineFormset, or similar.
         fk_name = formset.ct_fk_field.name
     # Look up the revision data.
     revision_versions = version.revision.version_set.all()
     related_versions = dict([
         (related_version.object_id, related_version)
         for related_version in revision_versions
         if ContentType.objects.get_for_id(related_version.content_type_id).
         model_class() == formset.model and unicode(
             related_version.field_dict[fk_name]) == unicode(object_id)
     ])
     return related_versions
Esempio n. 5
0
    def get_form_list(self):
        if not hasattr(self, '_form_list'):
            init_form_list = SortedDict()

            assert len(
                self.wizard_form_list) > 0, 'at least one form is needed'

            for i, form in enumerate(self.wizard_form_list):
                init_form_list[dutils.unicode(form[0])] = form[1]

            self._form_list = init_form_list

        return self._form_list
Esempio n. 6
0
 def get_context(self):
     context = super(ChangePasswordView, self).get_context()
     helper = FormHelper()
     helper.form_tag = False
     helper.include_media = False
     self.form.helper = helper
     context.update({
         'title': _('Change password: %s') % escape(dutils.unicode(self.obj)),
         'form': self.form,
         'has_delete_permission': False,
         'has_change_permission': True,
         'has_view_permission': True,
         'original': self.obj,
     })
     return context
Esempio n. 7
0
    def setup(self):
        BaseWidget.setup(self)

        bookmark = self.cleaned_data['bookmark']
        model = bookmark.content_type.model_class()
        data = QueryDict(bookmark.query)
        self.bookmark = bookmark

        if not self.title:
            self.title = dutils.unicode(bookmark)

        req = self.make_get_request("", data.items())
        self.list_view = self.get_view_class(ListAdminView,
                                             model,
                                             list_per_page=10,
                                             list_editable=[])(req)
Esempio n. 8
0
    def instance_form(self, **kwargs):
        u'''
        返回formset对象实例
        '''
        formset = self.get_formset(**kwargs)
        attrs = {
            'instance': self.model_instance,
            'queryset': self.style == 'new' and [] or 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:
                    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 = dutils.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)
                        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
Esempio n. 9
0
 def pre_save(self, model_instance, add):
     value = dutils.unicode(self.create_slug(model_instance, add))
     setattr(model_instance, self.attname, value)
     return value