Exemplo 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 to_unicode(related_obj.pk) in related_versions:
                initial.append(
                    related_versions.pop(to_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 to_range_list(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
            if sys.version < '3':
                helper.filter(basestring).wrap(InlineDiffField)
            else:
                helper.filter(str).wrap(InlineDiffField)

            fake_admin_class = type(str('%s%sFakeAdmin' % (self.opts.app_label, self.opts.model_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)
Exemplo n.º 2
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=to_unicode(self.org_obj.pk))

        self.prepare_form()
Exemplo n.º 3
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 = to_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)
Exemplo 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 + '_' + formset.fk.rel.get_related_field().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 to_unicode(related_version.field_dict[fk_name]) == to_unicode(object_id)])
     return related_versions
Exemplo n.º 5
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(to_unicode(self.obj)),
         'form':
         self.form,
         'has_delete_permission':
         False,
         'has_change_permission':
         True,
         'has_view_permission':
         True,
         'original':
         self.obj,
     })
     return context
Exemplo n.º 6
0
 def post_response(self):
     self.message_user(_('The %(model)s "%(name)s" was recovered successfully. You may edit it again below.') %
                       {"model": to_force_unicode(self.opts.verbose_name), "name": to_unicode(self.new_obj)}, 'success')
     return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk))
Exemplo n.º 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
        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(readonly_field).verbose_name
                            value = to_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
Exemplo n.º 8
0
    def get_nav_menu(self):
        site_menu = list(self.get_site_menu() or [])
        had_urls = []

        def get_url(menu, had_urls):
            if 'url' in menu:
                had_urls.append(menu['url'])
            if 'menus' in menu:
                for m in menu['menus']:
                    get_url(m, had_urls)

        get_url({'menus': site_menu}, had_urls)

        nav_menu = OrderedDict()

        for model, model_admin in self.admin_site._registry.items():
            if getattr(model_admin, 'hidden_menu', False):
                continue
            app_label = model._meta.app_label
            app_icon = None
            model_dict = {
                'title': to_unicode(capfirst(model._meta.verbose_name_plural)),
                'url': self.get_model_url(model, "changelist"),
                'icon': self.get_model_icon(model),
                'perm': self.get_model_perm(model, 'view'),
                'order': model_admin.order,
            }
            if model_dict['url'] in had_urls:
                continue

            app_key = "app:%s" % app_label
            if app_key in nav_menu:
                nav_menu[app_key]['menus'].append(model_dict)
            else:
                # Find app title
                app_title = to_unicode(app_label.title())
                if app_label.lower() in self.apps_label_title:
                    app_title = self.apps_label_title[app_label.lower()]
                else:
                    app_title = to_unicode(
                        apps.get_app_config(app_label).verbose_name)
                # find app icon
                if app_label.lower() in self.apps_icons:
                    app_icon = self.apps_icons[app_label.lower()]

                nav_menu[app_key] = {
                    'title': app_title,
                    'menus': [model_dict],
                }

            app_menu = nav_menu[app_key]
            if app_icon:
                app_menu['first_icon'] = app_icon
            elif ('first_icon' not in app_menu or app_menu['first_icon']
                  == self.default_model_icon) and model_dict.get('icon'):
                app_menu['first_icon'] = model_dict['icon']

            if 'first_url' not in app_menu and model_dict.get('url'):
                app_menu['first_url'] = model_dict['url']

        for menu in nav_menu.values():
            menu['menus'].sort(key=sortkeypicker(['order', 'title']))

        nav_menu = nav_menu.values()
        # nav_menu.sort(key=lambda x: x['title'])

        site_menu.extend(sorted(nav_menu, key=lambda x: x['title']))

        return site_menu
Exemplo n.º 9
0
 def valid_value(self, value):
     value = self.prepare_value(value)
     for k, v in self.choices:
         if value == to_unicode(k):
             return True
     return False