Ejemplo n.º 1
0
def edit_permissions(modeladmin, request, queryset):
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has the permission to edit permissions
    if not (
        request.user.is_superuser
        or request.user.has_perm("authority.change_permission")
        or request.user.has_perm("authority.change_foreign_permissions")
    ):
        raise PermissionDenied

    inline = ActionPermissionInline(queryset.model, modeladmin.admin_site)
    formsets = []
    for obj in queryset:
        prefixes = {}
        FormSet = inline.get_formset(request, obj)
        prefix = "%s-%s" % (FormSet.get_default_prefix(), obj.pk)
        prefixes[prefix] = prefixes.get(prefix, 0) + 1
        if prefixes[prefix] != 1:
            prefix = "%s-%s" % (prefix, prefixes[prefix])
        if request.POST.get("post"):
            formset = FormSet(
                data=request.POST, files=request.FILES, instance=obj, prefix=prefix
            )
        else:
            formset = FormSet(instance=obj, prefix=prefix)
        formsets.append(formset)

    media = modeladmin.media
    inline_admin_formsets = []
    for formset in formsets:
        fieldsets = list(inline.get_fieldsets(request))
        inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
        inline_admin_formsets.append(inline_admin_formset)
        media = media + inline_admin_formset.media

    if request.POST.get("post"):
        if all_valid(formsets):
            for formset in formsets:
                formset.save()
        else:
            modeladmin.message_user(
                request,
                "; ".join(
                    err.as_text() for formset in formsets for err in formset.errors
                ),
            )
        # redirect to full request path to make sure we keep filter
        return HttpResponseRedirect(request.get_full_path())

    context = {
        "errors": ActionErrorList(formsets),
        "title": ugettext("Permissions for %s") % force_text(opts.verbose_name_plural),
        "inline_admin_formsets": inline_admin_formsets,
        "app_label": app_label,
        "change": True,
        "form_url": mark_safe(""),
        "opts": opts,
        "target_opts": queryset.model._meta,
        "content_type_id": ContentType.objects.get_for_model(queryset.model).id,
        "save_as": False,
        "save_on_top": False,
        "is_popup": False,
        "media": mark_safe(media),
        "show_delete": False,
        "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
        "queryset": queryset,
        "object_name": force_text(opts.verbose_name),
    }
    template_name = getattr(
        modeladmin,
        "permission_change_form_template",
        [
            "admin/%s/%s/permission_change_form.html"
            % (app_label, opts.object_name.lower()),
            "admin/%s/permission_change_form.html" % app_label,
            "admin/permission_change_form.html",
        ],
    )
    return render_to_response(template_name, context, request)
Ejemplo n.º 2
0
    def change_view(self, request, object_id, extra_context=None, **kwargs):
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta
        obj = self.get_object(request, unquote(object_id))

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') %
                          {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})

        if request.method == 'POST' and "_saveasnew" in request.POST:
            return self.add_view(request, form_url='../add/')

        ModelForm = self.get_form(request, obj)
        formsets = []

        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)

            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj

            prefixes = {}

            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       self.get_inline_instances(request)):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1

                if prefixes[prefix] != 1:
                    prefix = "{0}-{1}".format(prefix, prefixes[prefix])
                formset = FormSet(request.POST, request.FILES,
                                  instance=new_object, prefix=prefix,
                                  queryset=inline.queryset(request))

                formsets.append(formset)

                for inline in self.get_inline_instances(request):
                    # If this is the inline that matches this formset, and
                    # we have some nested inlines to deal with, then we need
                    # to get the relevant formset for each of the forms in
                    # the current formset.
                    if inline.inlines and inline.model == formset.model:
                        for nested in inline.inline_instances:
                            for the_form in formset.forms:
                                InlineFormSet = nested.get_formset(request, the_form.instance)
                                prefix = "{0}-{1}".format(the_form.prefix,
                                                          InlineFormSet.get_default_prefix())
                                formsets.append(InlineFormSet(request.POST, request.FILES,
                                                              instance=the_form.instance,
                                                              prefix=prefix))
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()

                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)

                change_message = self.construct_change_message(request, form, formsets)
                self.log_change(request, new_object, change_message)

                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=obj)
            prefixes = {}

            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       self.get_inline_instances(request)):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "{0}-{1}".format(prefix, prefixes[prefix])
                formset = FormSet(instance=obj, prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request, obj),
                                      model_admin=self)
        media = self.media + adminForm.media
        inline_admin_formsets = []

        for inline, formset in zip(self.get_inline_instances(request), formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets,
                                                              readonly, model_admin=self)
            if inline.inlines:
                for form in formset.forms:
                    if form.instance.pk:
                        instance = form.instance
                    else:
                        instance = None

                    form.inlines = inline.get_inlines(request, instance, prefix=form.prefix)

                inline_admin_formset.inlines = inline.get_inlines(request)

            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.REQUEST,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }

        context.update(extra_context or {})

        return self.render_change_form(request, context, change=True, obj=obj)
Ejemplo n.º 3
0
    def rev_view(self, request, object_id, revision, extra_context=None):
        """mostly taken from `self.change_view`."""
        model = self.model
        opts = model._meta

        try:
            obj = model._default_manager.rev(revision).get(
                pk=unquote(object_id))
        except model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': force_unicode(opts.verbose_name),
                    'key': escape(object_id)
                })

        if request.method == 'POST' and request.POST.has_key("_saveasnew"):
            return self.add_view(request, form_url='../../add/')

        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == 'POST':
            raise Exception, "this should not happen"

        else:
            form = ModelForm(instance=obj)
            for FormSet in self.get_formsets(request, obj):
                formset = FormSet(instance=obj)
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
                                      self.prepopulated_fields)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': request.REQUEST.has_key('_popup'),
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       change=True,
                                       obj=obj,
                                       form_url='../../')
Ejemplo n.º 4
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        try:
            # get the default template response
            template_response = super(MpolynomModelAdmin, self).change_view(
                request, object_id, form_url, extra_context)
            # hide buttons
            if not request.user.is_superuser:
                if object_id:
                    obj = Mpolynom.objects.get(pk=object_id)
                    if obj:
                        if (obj.status == 'new_comments'
                                or obj.status == 'approved'):
                            # hide the div that contains the save and
                            # delete buttons
                            template_response.content = (
                                template_response.rendered_content.replace(
                                    '<div class="submit-row">',
                                    '<div class="submit-row" style="display: none">'
                                ))
            return template_response
        except (IntegrityError, DatabaseError) as e:
            if (str(e) ==
                    'UNIQUE constraint failed: search_mpolynom.structure_name'
                ):
                e = '''Structure name already exists! Check if the M-polynomial 
                    already exists in the database.'''
            model = self.model
            opts = model._meta
            formsets = []
            inline_instances = self.get_inline_instances(request, None)
            form = MpolynomAdminForm(request.POST, request.FILES)
            form.is_valid()
            # make faked nonfield error
            form._errors[NON_FIELD_ERRORS] = form.error_class([e])
            # We may handle exception here (just to save indentation)
            adminForm = helpers.AdminForm(
                form,
                list(self.get_fieldsets(request)),
                self.get_prepopulated_fields(request),
                self.get_readonly_fields(request),
                model_admin=self)
            media = self.media + adminForm.media

            inline_admin_formsets = []
            for inline, formset in zip(inline_instances, formsets):
                fieldsets = list(inline.get_fieldsets(request))
                readonly = list(inline.get_readonly_fields(request))
                prepopulated = dict(inline.get_prepopulated_fields(request))
                inline_admin_formset = helpers.InlineAdminFormSet(
                    inline,
                    formset,
                    fieldsets,
                    prepopulated,
                    readonly,
                    model_admin=self)
                inline_admin_formsets.append(inline_admin_formset)
                media = media + inline_admin_formset.media
            context = {
                'title': _('Add %s') % force_text(opts.verbose_name),
                'adminform': adminForm,
                'is_popup': IS_POPUP_VAR in request,
                'media': media,
                'inline_admin_formsets': inline_admin_formsets,
                'errors': helpers.AdminErrorList(form, formsets),
                'app_label': opts.app_label,
                'preserved_filters': self.get_preserved_filters(request),
            }
            context.update(extra_context or {})
            return self.render_change_form(request,
                                           context,
                                           form_url=form_url,
                                           add=True)
Ejemplo n.º 5
0
    def render_revision_form(self,
                             request,
                             obj,
                             version,
                             context,
                             revert=False,
                             recover=False):
        """Renders the object revision form."""
        model = self.model
        opts = model._meta
        object_id = obj.pk
        # Generate the model form.
        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == "POST":
            # This section is copied directly from the model admin change view
            # method.  Maybe one day there will be a hook for doing this better.
            form = ModelForm(request.POST,
                             request.FILES,
                             instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
                # HACK: If the value of a file field is None, remove the file from the model.
                for field in new_object._meta.fields:
                    if isinstance(field, models.FileField
                                  ) and form.cleaned_data[field.name] is None:
                        setattr(new_object, field.name, None)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                # Hack the formset to stuff in the new data.
                related_versions = self.get_related_versions(
                    obj, version, FormSet)
                formset.related_versions = related_versions
                new_forms = formset.forms[:len(related_versions)]
                for formset_form in formset.forms[len(related_versions):]:
                    if formset_form.fields["DELETE"].clean(
                            formset_form._raw_value("DELETE")):
                        new_forms.append(formset_form)
                formset.forms = new_forms

                def total_form_count_hack(count):
                    return lambda: count

                formset.total_form_count = total_form_count_hack(
                    len(new_forms))
                # Add this hacked formset to the form.
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    # HACK: If the value of a file field is None, remove the file from the model.
                    related_objects = formset.save(commit=False)
                    for related_obj, related_form in zip(
                            related_objects, formset.saved_forms):
                        for field in related_obj._meta.fields:
                            if isinstance(
                                    field, models.FileField
                            ) and related_form._raw_value(field.name) is None:
                                related_info = formset.related_versions.get(
                                    unicode(related_obj.pk))
                                if related_info:
                                    setattr(
                                        related_obj, field.name,
                                        related_info.field_dict[field.name])
                        related_obj.save()
                    formset.save_m2m()
                change_message = _(
                    u"Reverted to previous version, saved on %(datetime)s") % {
                        "datetime":
                        format(version.revision.date_created,
                               _(settings.DATETIME_FORMAT))
                    }
                self.log_change(request, new_object, change_message)
                self.message_user(
                    request,
                    _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.'
                      ) % {
                          "model": force_unicode(opts.verbose_name),
                          "name": unicode(obj)
                      })
                # Redirect to the model change form.
                if revert:
                    return HttpResponseRedirect("../../")
                elif recover:
                    return HttpResponseRedirect("../../%s/" % object_id)
                else:
                    assert False
        else:
            # This is a mutated version of the code in the standard model admin
            # change_view.  Once again, a hook for this kind of functionality
            # would be nice.  Unfortunately, it results in doubling the number
            # of queries required to construct the formets.
            form = ModelForm(instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       self.inline_instances):
                # This code is standard for creating the formset.
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                # Now we hack it to push in the data from the revision!
                initial = []
                related_versions = self.get_related_versions(
                    obj, version, FormSet)
                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))
                ]

                def total_form_count_hack(count):
                    return lambda: count

                formset.total_form_count = total_form_count_hack(len(initial))
                # Add this hacked formset to the form.
                formsets.append(formset)
        # Generate admin form helper.
        adminForm = helpers.AdminForm(form,
                                      self.get_fieldsets(request, obj),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request, obj),
                                      model_admin=self)
        media = self.media + adminForm.media
        # Generate formset helpers.
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        # Generate the context.
        context.update({
            "adminform":
            adminForm,
            "object_id":
            object_id,
            "original":
            obj,
            "is_popup":
            False,
            "media":
            mark_safe(media),
            "inline_admin_formsets":
            inline_admin_formsets,
            "errors":
            helpers.AdminErrorList(form, formsets),
            "app_label":
            opts.app_label,
            "add":
            False,
            "change":
            True,
            "has_add_permission":
            self.has_add_permission(request),
            "has_change_permission":
            self.has_change_permission(request, obj),
            "has_delete_permission":
            self.has_delete_permission(request, obj),
            "has_file_field":
            True,
            "has_absolute_url":
            False,
            "ordered_objects":
            opts.get_ordered_objects(),
            "form_url":
            mark_safe(request.path),
            "opts":
            opts,
            "content_type_id":
            ContentType.objects.get_for_model(self.model).id,
            "save_as":
            False,
            "save_on_top":
            self.save_on_top,
            "changelist_url":
            reverse("%s:%s_%s_changelist" %
                    (self.admin_site.name, opts.app_label, opts.module_name)),
            "change_url":
            reverse("%s:%s_%s_change" %
                    (self.admin_site.name, opts.app_label, opts.module_name),
                    args=(obj.pk, )),
            "history_url":
            reverse("%s:%s_%s_history" %
                    (self.admin_site.name, opts.app_label, opts.module_name),
                    args=(obj.pk, )),
            "recoverlist_url":
            reverse("%s:%s_%s_recoverlist" %
                    (self.admin_site.name, opts.app_label, opts.module_name))
        })
        # Render the form.
        if revert:
            form_template = self.revision_form_template
        elif recover:
            form_template = self.recover_form_template
        else:
            assert False
        return render_to_response(form_template, context,
                                  template.RequestContext(request))
Ejemplo n.º 6
0
    def change_view(self, request, object_id, extra_context=None):
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        try:
            obj = model._default_manager.get(pk=object_id)
        except model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})

        if request.method == 'POST' and request.POST.has_key("_saveasnew"):
            return self.add_view(request, form_url='../../add/')

        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            for FormSet in self.get_formsets(request, new_object):
                formset = FormSet(request.POST, request.FILES,
                                  instance=new_object)
                formsets.append(formset)

            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)
                
                change_message = self.construct_change_message(request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)
                
        else:
            form = ModelForm(instance=obj)
            for FormSet in self.get_formsets(request, obj):
                formset = FormSet(instance=obj)
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        
        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': request.REQUEST.has_key('_popup'),
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, change=True, obj=obj)
Ejemplo n.º 7
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        tab_language = get_language_from_request(request, None)
        to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
                                   
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        obj = self.get_object(request, unquote(object_id))

        if not self.has_change_permission(request, obj):
            messages.warning(request, _("You have no permissions to change %(name)s") % {"name": obj})
            if request.GET.get('destination'):
                dest_url = self.parse_destination(request, obj)
            else:
                dest_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name),  current_app=self.admin_site.name)
            return HttpResponseRedirect(dest_url)
        
        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})

        request.scms['page_type'] = obj.type
        request.scms['page'] = obj
        #if request.method == 'POST' and "_saveasnew" in request.POST:
            #raise PermissionDenied
            # Не реализовано
            #if not request.user.is_superuser and 'create' in scms.site.get_content_type(obj.type).permissions:
            #    return self.add_view(request, form_url='../add/%s' %  obj.type, current_app=self.admin_site.name)
            #else:
            #    raise PermissionDenied

        ModelForm = self.get_form(request, obj)
        formsets = []
        inline_instances = scms.site.get_content_type(obj.type).get_fields(obj)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj, language=tab_language)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
                 # Возвращается просто объект страницы, но запись в БД еще не происходила
                 # тк еще надо проверь корректность inline ов
            else:
                form_validated = False
                new_object = obj
            
            for inline in inline_instances:
                inline.init(self.model, self.admin_site)
                formset = inline.get_plugin_formset(request, obj, instance=new_object)
                formsets.append(formset)

            if all_valid(formsets) and form_validated:
                if "_saveasnew" in request.POST:
                    new_object = self.copy_page(new_object)

                self.save_related(request, form, formsets, True)
                self.save_model(request, new_object, form, True)
                change_message = self.construct_change_message(request, form, formsets)
                self.log_change(request, new_object, change_message)
                response = self.response_change(request, new_object) # стандартный обработчик
                if tab_language and response.status_code == 302 and response._headers['location'][1] == request.path:
                    location = response._headers['location']
                    response._headers['location'] = (location[0], "%s?language=%s" % (location[1], tab_language))
                return response

        else:
            form = ModelForm(instance=obj, language=tab_language)
      
            for inline in inline_instances:
                inline.init(self.model, self.admin_site)
                formset = inline.get_plugin_formset(request, None, instance=obj)
                formsets.append(formset)

        fieldsets = self.get_fieldsets(request, obj) 
                
        adminForm = helpers.AdminForm(
            form,
            list(self.get_fieldsets(request, obj)),
            self.get_prepopulated_fields(request, obj),
            self.get_readonly_fields(request, obj),
            model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            prepopulated = dict(inline.get_prepopulated_fields(request, obj))
            inline_formset = helpers.InlineAdminFormSet(inline, formset,
                fieldsets, prepopulated, readonly, model_admin=self)
            inline_admin_formsets.append(inline_formset)
            media = media + inline_formset.media
        
        fullobj = form.instance.full_load(language=tab_language)
        
        # context = {
        #     'title': _('Change %s') % force_text(opts.verbose_name), #TODO: указывать тип создаваемой страницы
        #     'adminform': adminForm,
        #     'object_id': object_id,
        #     'original': obj,
        #     'is_popup': "_popup" in request.GET or "_popup" in request.POST,
        #     'media': media,
        #     'inline_admin_formsets': inline_admin_formsets,
        #     'errors': helpers.AdminErrorList(form, formsets),
        #     'app_label': opts.app_label,
        #     #TODO!!!'root_path': self.admin_site.root_path,
        #     'view_path': fullobj and fullobj.link or None ,
        #     'destination': self.parse_destination(request, obj),
        #     'has_permission': True,
        #     'breadcrumbs': self.model(id=obj.parent_id).full_load().parents + [obj.full_load()],
        # }

        context = dict(
            self.admin_site.each_context(request),
            title=_('Change %s') % opts.verbose_name,
            adminform=adminForm,
            object_id=object_id,
            original=obj,
            is_popup=(IS_POPUP_VAR in request.POST or
                      IS_POPUP_VAR in request.GET),
            to_field=to_field,
            media=media,
            inline_admin_formsets=inline_admin_formsets,
            errors=helpers.AdminErrorList(form, formsets),
            preserved_filters=self.get_preserved_filters(request),
            view_path=fullobj and fullobj.link or None ,
            breadcrumbs=list(obj.get_parents()) + [obj.full_load(tab_language)],
            has_permission=True,            
            destination=self.parse_destination(request, obj),
        )

        context = self.update_language_tab_context(request, None, context)

        extra_context = self.update_language_tab_context(request, None, extra_context)
        extra_context['destination'] = request.GET.get('destination', None)
        form_url = form_url
        # extra_context['breadcrumbs'] = self.model(id=parent_id).full_load(tab_language).parents

        context.update(extra_context or {})

        return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
Ejemplo n.º 8
0
    def mass_change_view(self,
                         request,
                         comma_separated_object_ids,
                         extra_context=None):
        """The 'mass change' admin view for this model."""
        global new_object
        model = self.model
        opts = model._meta

        object_ids = comma_separated_object_ids.split(',')
        object_id = object_ids[0]

        try:
            obj = self.queryset(request).get(pk=unquote(object_id))
        except model.DoesNotExist:
            obj = None

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': force_unicode(opts.verbose_name),
                    'key': escape(object_id)
                })

        if request.method == 'POST' and request.POST.has_key("_saveasnew"):
            return self.add_view(request, form_url='../add/')

        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == 'POST':
            objects_count = 0
            changed_count = 0
            objects = self.queryset(request).filter(pk__in=object_ids)
            for obj in objects:
                objects_count += 1
                form = ModelForm(request.POST, request.FILES, instance=obj)

                exclude = []
                for fieldname, field in form.fields.items():
                    mass_change_checkbox = '_mass_change_%s' % fieldname
                    if not (request.POST.has_key(mass_change_checkbox)
                            and request.POST[mass_change_checkbox] == 'on'):
                        exclude.append(fieldname)
                for exclude_fieldname in exclude:
                    del form.fields[exclude_fieldname]

                if form.is_valid():
                    form_validated = True
                    new_object = self.save_form(request, form, change=True)
                else:
                    form_validated = False
                    new_object = obj
                prefixes = {}
                for FormSet in self.get_formsets(request, new_object):
                    prefix = FormSet.get_default_prefix()
                    prefixes[prefix] = prefixes.get(prefix, 0) + 1
                    if prefixes[prefix] != 1:
                        prefix = "%s-%s" % (prefix, prefixes[prefix])
                    mass_change_checkbox = '_mass_change_%s' % prefix
                    if request.POST.has_key(
                            mass_change_checkbox
                    ) and request.POST[mass_change_checkbox] == 'on':
                        formset = FormSet(request.POST,
                                          request.FILES,
                                          instance=new_object,
                                          prefix=prefix)
                        formsets.append(formset)

                if all_valid(formsets) and form_validated:
                    self.admin_obj.save_model(request,
                                              new_object,
                                              form,
                                              change=True)
                    # self.save_model(request, new_object, form, change=True)
                    form.save_m2m()
                    for formset in formsets:
                        self.save_formset(request, form, formset, change=True)

                    change_message = self.construct_change_message(
                        request, form, formsets)
                    self.log_change(request, new_object, change_message)
                    changed_count += 1

            if changed_count == objects_count:
                return self.response_change(request, new_object)
            else:
                raise Exception(
                    'Some of the selected objects could\'t be changed.')

        else:
            form = ModelForm(instance=obj)
            prefixes = {}
            for FormSet in self.get_formsets(request, obj):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj, prefix=prefix)
                formsets.append(formset)

            adminForm = helpers.AdminForm(form,
                                          self.get_fieldsets(request, obj),
                                          self.prepopulated_fields)
            media = self.media + adminForm.media

            inline_admin_formsets = []
            for inline, formset in zip(self.inline_instances, formsets):
                fieldsets = list(inline.get_fieldsets(request, obj))
                inline_admin_formset = helpers.InlineAdminFormSet(
                    inline, formset, fieldsets)
                inline_admin_formsets.append(inline_admin_formset)
                media = media + inline_admin_formset.media

            context = {
                'title': _('Change %s') % force_unicode(opts.verbose_name),
                'adminform': adminForm,
                'object_id': object_id,
                'original': obj,
                'is_popup': request.REQUEST.has_key('_popup'),
                'media': mark_safe(media),
                'inline_admin_formsets': inline_admin_formsets,
                'errors': helpers.AdminErrorList(form, formsets),
                'root_path': self.admin_site.root_path,
                'app_label': opts.app_label,
                'object_ids': comma_separated_object_ids,
            }
            context.update(extra_context or {})
            return self.render_mass_change_form(request,
                                                context,
                                                change=True,
                                                obj=obj)
Ejemplo n.º 9
0
    def _nested_formsets(self,
                         request,
                         admin,
                         instance,
                         create_formset,
                         prefixes=None,
                         qs_field=None):
        """Collect all formsets recursively"""
        # pylint: disable=too-many-arguments
        # pylint: disable=too-many-locals
        # pylint: disable=too-many-locals

        formsets = []
        inline_admin_formsets = []
        media = []
        prefixes = prefixes or {}
        if not hasattr(admin, 'inline_instances'):
            admin.inline_instances = admin.get_inline_instances(request)
        for form_set, inline in admin.get_formsets_with_inlines(request):
            prefix = form_set.get_default_prefix()
            prefixes[prefix] = prefixes.get(prefix, 0) + 1
            if prefixes[prefix] != 1:
                prefix = "%s-%s" % (prefix, prefixes[prefix])

            new_qs_field = None
            if qs_field:
                # if we were passed a qs_field, grab the qs from their directly to avoid
                # hitting the database again
                qset = getattr(instance, qs_field).all()
            elif hasattr(inline, 'prefetch'):
                # we prefetch the related field, then pass that field recursively
                qset = inline.get_queryset(request).prefetch_related(
                    inline.prefetch)
                new_qs_field = inline.prefetch
            else:
                # normal qs
                qset = inline.get_queryset(request)
            formset = create_formset(form_set, request, admin, instance,
                                     prefix, qset)
            formsets.append(formset)

            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline,
                formset,
                fieldsets,
                readonly_fields=readonly,
                model_admin=admin)
            inline_admin_formsets.append(inline_admin_formset)
            media.append(inline_admin_formset.media)

            for form in formset.forms:
                new_formsets, new_inline_admin_formsets, new_media = \
                    self._nested_formsets(request, inline, form.instance,
                                          create_formset, prefixes=prefixes, qs_field=new_qs_field)
                formsets.extend(new_formsets)
                form.inline_admin_formsets = new_inline_admin_formsets
                media.extend(new_media)

        return formsets, inline_admin_formsets, media
Ejemplo n.º 10
0
    def change_view(self, request, object_id, extra_context=None):
        self.model._needs_content_types()

        # Recognize frontend editing requests
        # This is done here so that the developer does not need to add additional entries to
        # urls.py or something...
        res = FRONTEND_EDITING_MATCHER.search(object_id)

        if res:
            return self._frontend_editing_view(request, res.group(1), res.group(2), res.group(3))

        opts = self.model._meta

        try:
            obj = self.model._default_manager.get(pk=unquote(object_id))
        except self.model.DoesNotExist:
            raise Http404

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if "revision" in request.GET:
            from reversion.models import Revision

            try:
                revision = Revision.objects.get(pk=request.GET['revision'])
            except Revision.DoesNotExist:
                raise Http404

            self.message_user(request, _('Click save to replace the current content with this version'))
        else:
            revision = None

        ModelForm = self.get_form(
            request,
            obj,
            # NOTE: Fields *MUST* be set to None to avoid breaking
            # django.contrib.admin.option.ModelAdmin's default get_form()
            # will generate a very abbreviated field list which will cause
            # KeyErrors during clean() / save()
            fields=None,
            formfield_callback=self._formfield_callback(request=request),
            form=self.form
        )

        # generate a formset type for every concrete content type
        inline_formset_types = self._get_inline_formset_types(request)

        formsets = []
        if request.method == 'POST':
            FORM_DATA = {}
            model_form = ModelForm(request.POST, request.FILES, instance=obj)

            inline_formsets = [
                formset_class(request.POST, request.FILES, instance=obj,
                    prefix=content_type.__name__.lower())
                for content_type, formset_class in inline_formset_types]

            if model_form.is_valid():
                form_validated = True
                new_object = self.save_form(request, model_form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet in self.get_formsets(request, new_object):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST, request.FILES,
                                  instance=new_object, prefix=prefix)
                formsets.append(formset)

            if all_valid(inline_formsets+formsets) and form_validated:
                #model_form.save(commit=False)
                model_form.save_m2m()
                for formset in inline_formsets:
                    formset.save()
                #model_form.save(commit=True)
                self.save_model(request, new_object, model_form, change=True)
                for formset in formsets:
                    self.save_formset(request, model_form, formset, change=True)

                msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
                if request.POST.has_key("_continue"):
                    self.message_user(request, msg + ' ' + _("You may edit it again below."))
                    return HttpResponseRedirect('.')
                elif request.POST.has_key('_addanother'):
                    self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
                    return HttpResponseRedirect("../add/")
                else:
                    self.message_user(request, msg)
                    return HttpResponseRedirect("../")
        elif revision:
            FORM_DATA = {}

            total_forms = dict(
                [(ct.__name__.lower(), 0) for ct in self.model._feincms_content_types]
            )

            for version in revision.version_set.all().select_related("content_type"):
                if version.object_version.object == obj:
                    FORM_DATA.update(version.field_dict)
                    continue

                version_prefix = "%s-%s" % (
                    version.content_type.model,
                    total_forms[version.content_type.model]
                )


                for k, v in version.field_dict.items():
                    form_key = "%s-%s" % (version_prefix, k)
                    assert form_key not in FORM_DATA
                    FORM_DATA[form_key] = v

                # defaultdict would be cleaner but this works with Python 2.4:
                total_forms[version.content_type.model] += 1


            for k, v in total_forms.items():
                FORM_DATA["%s-INITIAL_FORMS" % k] = v
                # TOTAL FORMS should be one for each actual object and one for
                # the "Add new" feature. We'll bump the total up if we actually
                # have existing content:
                if v:
                    FORM_DATA["%s-TOTAL_FORMS" % k] = v + 1
                else:
                    FORM_DATA["%s-TOTAL_FORMS" % k] = 0

            # BUG: This somehow does not correctly initialize the initial form for adding new content correctly
            model_form = ModelForm(FORM_DATA, instance=obj)
            inline_formsets = [
                formset_class(FORM_DATA, instance=obj, prefix=content_type.__name__.lower())
                for content_type, formset_class in inline_formset_types
            ]
            prefixes = {}
            for FormSet in self.get_formsets(request, obj):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj, prefix=prefix)
                formsets.append(formset)
        else:
            model_form = ModelForm(instance=obj)
            inline_formsets = [
                formset_class(instance=obj, prefix=content_type.__name__.lower())
                for content_type, formset_class in inline_formset_types
            ]
            prefixes = {}
            for FormSet in self.get_formsets(request, obj):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj, prefix=prefix)
                formsets.append(formset)

        # Prepare mapping of content types to their prettified names
        content_types = []
        for content_type in self.model._feincms_content_types:
            content_name = content_type._meta.verbose_name
            content_types.append((content_name, content_type.__name__.lower()))

        context = {}

        adminForm = helpers.AdminForm(model_form, self.get_fieldsets(request, obj),
            self.prepopulated_fields, self.get_readonly_fields(request, obj),
            model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media


        if hasattr(self.model, '_feincms_templates'):
            if 'template_key' not in self.show_on_top:
                self.show_on_top = ['template_key'] + list(self.show_on_top)

            context['available_templates'] = self.model._feincms_templates

        if hasattr(self.model, 'parent'):
            context['has_parent_attribute'] = True

        context.update({
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request, obj=obj),
            'has_delete_permission': self.has_delete_permission(request, obj=obj),
            'add': False,
            'change': obj.pk is not None,
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'opts': opts,
            'object': obj,
            'object_form': model_form,
            'adminform': adminForm,
            'inline_formsets': inline_formsets,
            'inline_admin_formsets': inline_admin_formsets,
            'content_types': content_types,
            'top_fields': [model_form[field] for field in self.show_on_top],
            'settings_fields': [field for field in model_form if field.name not in self.show_on_top],
            'media': media,
            'errors': helpers.AdminErrorList(model_form, inline_formsets),
            'FEINCMS_ADMIN_MEDIA': settings.FEINCMS_ADMIN_MEDIA,
            'FEINCMS_ADMIN_MEDIA_HOTLINKING': settings.FEINCMS_ADMIN_MEDIA_HOTLINKING,
        })

        return self.render_item_editor(request, obj, context)
Ejemplo n.º 11
0
    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta
        app_label = opts.app_label

        if not self.has_add_permission(request):
            raise PermissionDenied

        if self.has_change_permission(request, None):
            # redirect to list view
            post_url = '../'
        else:
            # Object list will give 'Permission Denied', so go back to admin home
            post_url = '../../../'

        ModelForm = self.get_form(request)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=False)
            else:
                form_validated = False
                new_object = self.model()
            for FormSet in self.get_formsets(request):
                formset = FormSet(
                    data=request.POST,
                    files=request.FILES,
                    instance=new_object,
                    save_as_new=request.POST.has_key("_saveasnew"))
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=False)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=False)

                self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            form = ModelForm(initial=dict(request.GET.items()))
            for FormSet in self.get_formsets(request):
                formset = FormSet(instance=self.model())
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
                                      self.prepopulated_fields)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': request.REQUEST.has_key('_popup'),
            'show_delete': False,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, add=True)
Ejemplo n.º 12
0
    def add_view(self, request, extra_context=None, form_url=None):
        opts = self.model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request,
            fields=None,
            formfield_callback=self._formfield_callback(request=request),
            form=self.form
        )

        inline_formset_types = self._get_inline_formset_types(request)
        formsets = []

        if request.method == 'POST':
            model_form = ModelForm(request.POST, request.FILES)

            if model_form.is_valid():
                form_validated = True
                new_object = self.save_form(request, model_form, change=False)
            else:
                form_validated = False
                new_object = self.model()

            inline_formsets = [
                formset_class(request.POST, request.FILES, instance=new_object,
                    prefix=content_type.__name__.lower())
                for content_type, formset_class in inline_formset_types]

            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request), self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST, files=request.FILES,
                    instance=new_object,
                    save_as_new=request.POST.has_key('_saveasnew'),
                    prefix=prefix, queryset=inline.queryset(request))
                formsets.append(formset)

            if all_valid(inline_formsets+formsets) and form_validated:
                self.save_model(request, new_object, model_form, change=False)
                model_form.save_m2m()
                for formset in inline_formsets:
                    formset.save()
                for formset in formsets:
                    self.save_formset(request, model_form, formset, change=False)

                msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)}
                if request.POST.has_key("_continue"):
                    self.message_user(request, msg + ' ' + _("You may edit it again below."))
                    return HttpResponseRedirect('../%s/' % new_object.pk)
                elif request.POST.has_key('_addanother'):
                    self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
                    return HttpResponseRedirect("../add/")
                else:
                    self.message_user(request, msg)
                    return HttpResponseRedirect("../")
        else:
            initial = dict(request.GET.items())
            model_form = ModelForm(initial=initial)
            inline_formsets = [
                formset_class(prefix=content_type.__name__.lower())
                for content_type, formset_class in inline_formset_types]

            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request), self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(),
                    prefix=prefix, queryset=inline.queryset(request))
                formsets.append(formset)

        # Prepare mapping of content types to their prettified names
        content_types = []
        for content_type in self.model._feincms_content_types:
            content_name = content_type._meta.verbose_name
            content_types.append((content_name, content_type.__name__.lower()))

        context = {}

        #media = self.media + model_form.media
        adminForm = helpers.AdminForm(model_form, list(self.get_fieldsets(request)),
            self.prepopulated_fields, self.get_readonly_fields(request),
            model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets,
                model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        if hasattr(self.model, '_feincms_templates'):
            if 'template_key' not in self.show_on_top:
                self.show_on_top = ['template_key'] + list(self.show_on_top)

            context['available_templates'] = self.model._feincms_templates

        if hasattr(self.model, 'parent'):
            context['has_parent_attribute'] = True

        context.update({
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request),
            'has_delete_permission': self.has_delete_permission(request),
            'add': True,
            'change': False,
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'opts': opts,
            'object': self.model(),
            'object_form': model_form,
            'adminform': adminForm,
            'inline_formsets': inline_formsets,
            'inline_admin_formsets': inline_admin_formsets,
            'content_types': content_types,
            'top_fields': [model_form[field] for field in self.show_on_top],
            'settings_fields': [field for field in model_form if field.name not in self.show_on_top],
            'media': media,
            'errors': helpers.AdminErrorList(model_form, inline_formsets),
            'FEINCMS_ADMIN_MEDIA': settings.FEINCMS_ADMIN_MEDIA,
            'FEINCMS_ADMIN_MEDIA_HOTLINKING': settings.FEINCMS_ADMIN_MEDIA_HOTLINKING,
        })

        return self.render_item_editor(request, None, context)
Ejemplo n.º 13
0
    def render_revision_form(self,
                             request,
                             obj,
                             version,
                             context,
                             revert=False,
                             recover=False):
        """Renders the object revision form."""
        model = self.model
        opts = model._meta
        object_id = obj.pk
        # Generate the model form.
        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == "POST":
            # This section is copied directly from the model admin change view
            # method.  Maybe one day there will be a hook for doing this better.
            form = ModelForm(request.POST,
                             request.FILES,
                             instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])

                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))

                # _ _ _ ____ ___ ____ _  _    ____ _  _ ___
                # | | | |__|  |  |    |__|    |  | |  |  |
                # |_|_| |  |  |  |___ |  |    |__| |__|  |
                # this is not copy pasted:
                # Strip extra empty forms from the formset.
                empty_forms = []
                post_keys = request.POST.keys()
                for f in formset.forms:
                    # the forms that can be removed, are not in the request.POST
                    # we can find them by their prefix
                    matches_prefix = lambda var: var.find(f.prefix
                                                          ) == 0 or None
                    if first_match(matches_prefix, post_keys) is None:
                        empty_forms.append(f)
                    else:
                        # the form must be cleaned, which they aren't yet because
                        # we just created them
                        f.full_clean()

                # modify form settings of formset.
                num_forms = formset.total_form_count() - len(empty_forms)
                formset.forms = filter(lambda x: x not in empty_forms,
                                       formset.forms)
                formset.total_form_count = lambda: num_forms
                # end of non copy pasted piece

                # Add this hacked formset to the form.
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)

                # _ _ _ ____ ___ ____ _  _    ____ _  _ ___
                # | | | |__|  |  |    |__|    |  | |  |  |
                # |_|_| |  |  |  |___ |  |    |__| |__|  |
                # this is not copy pasted:
                self.update_draft(version, request)

                change_message = _(u"Publisher message %(datetime)s") % {
                    "datetime":
                    format(version.revision.date_created,
                           _(settings.DATETIME_FORMAT))
                }
                self.log_change(request, new_object, change_message)
                self.message_user(
                    request,
                    _(u'%(model)s "%(name)s" publisher message.') % {
                        "model": force_unicode(opts.verbose_name),
                        "name": unicode(obj)
                    })

                # end of not copy pasted code

                # Redirect to the model change form.
                if revert:
                    return HttpResponseRedirect("../../")
                elif recover:
                    return HttpResponseRedirect("../../%s/" % object_id)
                else:
                    assert False
        else:
            # This is a mutated version of the code in the standard model admin
            # change_view.  Once again, a hook for this kind of functionality
            # would be nice.  Unfortunately, it results in doubling the number
            # of queries required to construct the formets.
            form = ModelForm(instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            prefixes = {}
            revision_versions = version.revision.version_set.all()
            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       self.inline_instances):
                # This code is standard for creating the formset.
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                # Now we hack it to push in the data from the revision!
                try:
                    fk_name = FormSet.fk.name
                except AttributeError:
                    # This is a GenericInlineFormset, or similar.
                    fk_name = FormSet.ct_fk_field.name

                # _ _ _ ____ ___ ____ _  _    ____ _  _ ___
                # | | | |__|  |  |    |__|    |  | |  |  |
                # |_|_| |  |  |  |___ |  |    |__| |__|  |
                # this is not copy pasted:
                related_versions = [
                    (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)
                ]

                # all items that do not have their id filled in must stay.
                # if they do in fact have an id, we only want the last one,
                # no duplicates.
                related_versions = [(key, value) for (key, value) in related_versions if key == 'None'] + \
                    dict([(key, value) for (key, value) in related_versions if key != 'None']).items()

                initial = []
                for related_obj in formset.queryset:
                    related_versions_dict = dict(related_versions)
                    if unicode(related_obj.pk) in related_versions_dict:
                        initial.append(
                            related_versions_dict.pop(unicode(
                                related_obj.pk)).field_dict)
                    else:
                        initial_data = model_to_dict(related_obj)
                        initial_data["DELETE"] = True
                        initial.append(initial_data)
                for (key, related_version) in related_versions:
                    initial_row = related_version.field_dict
                    try:
                        del initial_row["id"]
                    except KeyError:
                        # when multiple inlines with the same model but a different
                        # querysets are on a page, it could happen that we allready
                        # deleted the id.
                        pass

                    # we didn't convert related_versions to a dict so there can be
                    # duplicate keys in the thingy
                    if not initial_row in initial:
                        initial.append(initial_row)

                # end of non copy pasted piece

                # Reconstruct the forms with the new revision data.
                formset.initial = initial
                formset.forms = [
                    formset._construct_form(n) for n in xrange(len(initial))
                ]
                # Add this hacked formset to the form.
                formsets.append(formset)
        # Generate admin form helper.
        adminForm = helpers.AdminForm(form,
                                      self.get_fieldsets(request, obj),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request, obj),
                                      model_admin=self)
        media = self.media + adminForm.media
        # Generate formset helpers.
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        # Generate the context.
        context.update({
            "adminform":
            adminForm,
            "object_id":
            object_id,
            "original":
            obj,
            "is_popup":
            False,
            "media":
            mark_safe(media),
            "inline_admin_formsets":
            inline_admin_formsets,
            "errors":
            helpers.AdminErrorList(form, formsets),
            "app_label":
            opts.app_label,
            "add":
            False,
            "change":
            True,
            "has_add_permission":
            self.has_add_permission(request),
            "has_change_permission":
            self.has_change_permission(request, obj),
            "has_delete_permission":
            self.has_delete_permission(request, obj),
            "has_file_field":
            True,
            "has_absolute_url":
            getattr(self.model, 'get_absolute_url', False),
            "ordered_objects":
            opts.get_ordered_objects(),
            "form_url":
            mark_safe(request.path),
            "opts":
            opts,
            "content_type_id":
            ContentType.objects.get_for_model(self.model).id,
            "save_as":
            False,
            "save_on_top":
            self.save_on_top,
            "changelist_url":
            reverse("admin:%s_%s_changelist" %
                    (opts.app_label, opts.module_name)),
            "change_url":
            reverse("admin:%s_%s_change" % (opts.app_label, opts.module_name),
                    args=(obj.pk, )),
            "history_url":
            reverse("admin:%s_%s_history" % (opts.app_label, opts.module_name),
                    args=(obj.pk, )),
            "recoverlist_url":
            reverse("admin:%s_%s_recoverlist" %
                    (opts.app_label, opts.module_name))
        })

        # Render the form.
        if revert:
            form_template = self.revision_form_template
        elif recover:
            form_template = self.recover_form_template
        else:
            assert False
        return render_to_response(form_template, context,
                                  template.RequestContext(request))
Ejemplo n.º 14
0
    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta

        ModelForm = self.get_form(request)
        formsets = []
        inline_instances = self.get_inline_instances(request, None)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(
                    request, new_object):
                prefix = FormSet.get_default_prefix()
                # check if we're trying to create a new project by copying an existing one. If so
                # we ignore location and benchmark inlines
                if "_saveasnew" not in request.POST or prefix not in [
                        'benchmarks', 'rsr-location-content_type-object_id'
                ]:
                    # end of add although the following block is indented as a result
                    prefixes[prefix] = prefixes.get(prefix, 0) + 1
                    if prefixes[prefix] != 1 or not prefix:
                        prefix = "%s-%s" % (prefix, prefixes[prefix])
                    formset = FormSet(data=request.POST,
                                      files=request.FILES,
                                      instance=new_object,
                                      save_as_new="_saveasnew" in request.POST,
                                      prefix=prefix,
                                      queryset=inline.get_queryset(request))
                    formsets.append(formset)
            if self.all_valid_with_nesting(formsets) and form_validated:
                self.save_model(request, new_object, form, False)
                self.save_related(request, form, formsets, False)
                message = self.construct_change_message(request,
                                                        form,
                                                        formsets,
                                                        add=True)
                self.log_addition(request, new_object, message)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])

                formset = FormSet(instance=self.model(),
                                  prefix=prefix,
                                  queryset=inline.get_queryset(request))
                formsets.append(formset)

        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.get_prepopulated_fields(request),
                                      self.get_readonly_fields(request),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(inline.get_prepopulated_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              prepopulated,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_text(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': IS_POPUP_VAR in request.POST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            'preserved_filters': self.get_preserved_filters(request),
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Ejemplo n.º 15
0
    def change_view_popup(self, request, object_id, extra_context=None):
        "The 'change' admin view for reverted model."
        model = self.model
        opts = model._meta
        notabs = {'notabs': True}
        try:
            extra_context = extra_context.update(notabs)
        except:
            extra_context = notabs

        obj = self.get_object(request, unquote(object_id))

        revert_model_name = self.revert_model.__name__.lower()
        if hasattr(obj, revert_model_name):
            revert_obj = getattr(obj, revert_model_name)
            obj = revert_obj

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': force_unicode(opts.verbose_name),
                    'key': escape(object_id)
                })

        if request.method == 'POST' and "_saveasnew" in request.POST:
            return self.add_view(request, form_url='../add/')

        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))

                formsets.append(formset)

            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)

                change_message = self.construct_change_message(
                    request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=obj)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)

        adminForm = helpers.AdminForm(form,
                                      self.get_fieldsets(request, obj),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request, obj),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.REQUEST,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
            'has_change_permission': self.has_change_permission(request)
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, change=True, obj=obj)
Ejemplo n.º 16
0
    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []
        inline_instances = self.get_inline_instances(request)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST,
                                  files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, False)
                self.save_related(request, form, formsets, False)
                self.log_addition(request, new_object)
                log.info('The new object has %s id' % new_object.id)
                ## added
                print 'entered response_add soa'
                # saving soa id to LogBook
                if "log_id" in request.GET:
                    next = request.GET.get('next')
                    log_id = request.GET.get('log_id')
                    logbk = LogBook.objects.get(pk=log_id)
                    soa = SOA.objects.get(pk=new_object.id)
                    print 'saving new log id and soa id'
                    payment = Statements.objects.create(logbook=logbk, soa=soa)
                    payment.save()
                print 'save successful for new payment'
                print ' Saving SOA in group Engr'
                ### end add
                print 'inside what i want', new_object.id
                return HttpResponseRedirect(
                    '/admin/ccad/soa/%s' %
                    new_object.id)  #<-- changed to my new one
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(),
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)

        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.get_prepopulated_fields(request),
                                      self.get_readonly_fields(request),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(inline.get_prepopulated_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              prepopulated,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Ejemplo n.º 17
0
    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=False)
            else:
                form_validated = False
                new_object = self.model()
            for FormSet in self.get_formsets(request):
                formset = FormSet(data=request.POST, files=request.FILES,
                                  instance=new_object,
                                  save_as_new=request.POST.has_key("_saveasnew"))
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=False)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=False)
                
                self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)
            for FormSet in self.get_formsets(request):
                formset = FormSet(instance=self.model())
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)), self.prepopulated_fields)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': request.REQUEST.has_key('_popup'),
            'show_delete': False,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, add=True)
Ejemplo n.º 18
0
    def add_view(self, request, form_url='', extra_context=None):
        """
        This method is overriden in its entirety so that the ApiKey inline won't be
        displayed/parsed on the add_form page.
        """
        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []
        inline_instances = self.get_inline_instances(request)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()

            PANDA_SKIP_INLINES = """prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request), inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST, files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix, queryset=inline.queryset(request))
                formsets.append(formset)
            if all_valid(formsets) and form_validated:"""

            if form_validated:
                self.save_model(request, new_object, form, False)
                self.save_related(request, form, formsets, False)
                self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)

            PANDA_SKIP_INLINES = """prefixes = {}
            
            for FormSet, inline in zip(self.get_formsets(request), inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(), prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)"""

        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.get_prepopulated_fields(request),
                                      self.get_readonly_fields(request),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(inline.get_prepopulated_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              prepopulated,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            'email_enabled': config_value('EMAIL', 'EMAIL_ENABLED')
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Ejemplo n.º 19
0
    def i18n_change_view(self, request, object_id, language, extra=None):
        "The 'change' admin view for this model."
        cur_language = translation.get_language()
        translation.activate(language)
        model = self.model
        opts = model._meta
        self.lang = language

        obj = self.get_object(request, unquote(object_id))

        Tobj = self.get_i18n_object(request, unquote(object_id), obj, language)

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        master_language = get_translation_opt(self.model, 'master_language')
        if language == master_language:
            # redirect to instance admin on default language
            return HttpResponseRedirect('../')

        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r \
            does not exist.'                            ) % {'name': force_unicode(opts.verbose_name), \
            'key': escape(object_id)})

        if language not in dict(settings.LANGUAGES):
            raise Http404(_('Incorrect language %(l)s') % {'l': language})

        ModelForm = self.get_form(request, Tobj)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=Tobj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = Tobj
            prefixes = {}
            for FormSet, inline in zip(
                    self.get_formsets(request, new_object),
                    self.get_inline_instances(*get_inline_instances_args(
                        self, request, new_object))):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object._master,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)

            all_valid = True
            for fs in formsets:
                if not fs.is_valid():
                    all_valid = False

            if all_valid and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)

                change_message = \
                self.construct_change_message(request, form, formsets)
                self.log_change(request, new_object, change_message)
                self.lang = None
                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=Tobj)
            prefixes = {}
            for FormSet, inline in \
                zip(self.get_formsets(request, Tobj._master), \
                    self.get_inline_instances(*get_inline_instances_args(self, request, Tobj))):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=Tobj._master,
                                  prefix=prefix,
                                  queryset=None)
                formsets.append(formset)

        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.get_prepopulated_fields(request),
                                      self.get_readonly_fields(request),
                                      model_admin=self)
        media = self.media + adminForm.media

        def get_prepopulated_fields_inline(inline, request):
            # FIX for 1.3
            if hasattr(inline, 'get_prepopulated_fields'):
                prepopulated_fields = inline.get_prepopulated_fields(request)
            else:
                prepopulated_fields = inline.prepopulated_fields
            translatable_fields = get_translation_opt(inline.model,
                                                      'translatable_fields')
            for k, v in prepopulated_fields.items():
                if k not in translatable_fields or v not in translatable_fields:
                    prepopulated_fields.pop(k)
            return prepopulated_fields

        inline_admin_formsets = []
        for inline, formset in zip(
                self.get_inline_instances(
                    *get_inline_instances_args(self, request, obj)), formsets):
            if not hasattr(inline.model, '_translation_model'):
                continue
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(get_prepopulated_fields_inline(
                inline, request))
            inline_kwargs = {}
            # FIX for 1.3
            if '1.4' in get_django_version():
                inline_kwargs['model_admin'] = self
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline, formset, fieldsets, prepopulated, readonly,
                **inline_kwargs)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        translated_fields = []
        for f in obj._translation_model._transmeta.translatable_fields:
            try:
                v = getattr(obj, '_'.join((f, 'master')))
            except:
                v = getattr(
                    obj,
                    f,
                )
            v = v or ''
            if hasattr(v, 'replace'):
                v = v.replace("'", "&#39;").replace('"', "&quot;")
                v = v.replace('\r', '')
                v = v.replace('\n', '<br>')
            translated_fields.append((f, v))

        context = {
            'title': _('Translation %s') % force_unicode(opts.verbose_name),
            'tiny_mce': True,
            'adminform': adminForm,
            'original': obj,
            'translated_fields': translated_fields,
            'master_language': master_language,
            'is_popup': ('_popup' in request.REQUEST),
            'errors': admin.helpers.AdminErrorList(form, []),
            #'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
            'trans': True,
            'lang': language,
            'current_language': dict(settings.LANGUAGES)[language],
            'inline_admin_formsets': inline_admin_formsets,
            # override some values to provide an useful template
            'add': False,
            'change': True,
            'has_change_permission_orig': True,  # backup
            'has_add_permission': False,
            'has_change_permission': False,
            'has_delete_permission': False,  # hide delete link for now
            'has_file_field': True,
            'save_as': False,
            'opts': self.model._meta,
        }
        translation.activate(cur_language)
        self.lang = None
        ctx = RequestContext(request, current_app=self.admin_site.name)
        change_form_template = [
            "admin/%s/%s/change_form.html" %
            (opts.app_label, opts.object_name.lower()),
            CHANGE_TRANSLATION_TPL,
            "admin/%s/change_form.html" % opts.app_label,
            "admin/change_form.html",
        ]
        return render_to_response(change_form_template,
                                  context,
                                  context_instance=ctx)
Ejemplo n.º 20
0
    def _changeform_view(self, request, object_id, form_url, extra_context):
        add = object_id is None

        model = self.model
        opts = model._meta

        model_form = self.get_form(request)
        formsets = []

        if add:
            if not self.has_add_permission(request):
                raise PermissionDenied
            obj = None

        else:
            obj = self.get_object(request, unquote(object_id))

            if request.method == 'POST':
                if not self.has_change_permission(request, obj):
                    raise PermissionDenied
            else:
                if not self.has_view_or_change_permission(request, obj):
                    raise PermissionDenied

            if obj is None:
                return self._get_obj_does_not_exist_redirect(
                    request, opts, object_id)

        if request.method == 'POST':
            form = model_form(request.POST, request.FILES, instance=obj)
            form_validated = form.is_valid()
            if form_validated:
                new_object = self.save_form(request, form, change=not add)
            else:
                new_object = form.instance
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST,
                                  files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix)
                formsets.append(formset)
            formset_inline_tuples = zip(formsets,
                                        self.get_inline_instances(request))
            formset_inline_tuples = _remove_blank_reverse_inlines(
                new_object, formset_inline_tuples)
            formsets = [t[0] for t in formset_inline_tuples]
            if form_validated and not formsets:
                self.save_model(request, new_object, form, change=not add)
                self.save_related(request, form, formsets, change=not add)
                form.save_m2m()
                return self.response_add(request, new_object)
            elif form_validated and all_valid(formsets):
                # Here is the modified code.
                for formset, inline in formset_inline_tuples:
                    if not isinstance(inline, ReverseInlineModelAdmin):
                        continue
                    # The idea or this piece is coming from https://stackoverflow.com/questions/50910152/inline-formset-returns-empty-list-on-save.
                    # Without this, formset.save() was returning None for forms that
                    # haven't been modified
                    forms = [f for f in formset]
                    if not forms:
                        continue
                    obj = forms[0].save()
                    setattr(new_object, inline.parent_fk_name, obj)
                self.save_model(request, new_object, form, change=not add)
                self.save_related(request, form, formsets, change=not add)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=not add)

                # self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            if add:
                form = model_form(initial=initial)
                prefixes = {}
                for FormSet, inline in self.get_formsets_with_inlines(request):
                    prefix = FormSet.get_default_prefix()
                    prefixes[prefix] = prefixes.get(prefix, 0) + 1
                    if prefixes[prefix] != 1:
                        prefix = "%s-%s" % (prefix, prefixes[prefix])
                    formset = FormSet(instance=self.model(), prefix=prefix)
                    formsets.append(formset)
            else:
                form = model_form(instance=obj)
                formsets, inline_instances = self._create_formsets(request,
                                                                   obj,
                                                                   change=True)

        readonly_fields = self.get_readonly_fields(request, obj)
        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.prepopulated_fields,
                                      readonly_fields=readonly_fields,
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.get_inline_instances(request),
                                   formsets):
            fieldsets = list(inline.get_fieldsets(request))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline, formset, fieldsets, readonly_fields=readonly_fields)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        # Inherit the default context from admin_site
        context = self.admin_site.each_context(request)
        reverse_admin_context = {
            'title':
            _(('Change %s', 'Add %s')[add]) % force_text(opts.verbose_name),
            'adminform':
            adminForm,
            # 'is_popup': '_popup' in request.REQUEST,
            'is_popup':
            False,
            'original':
            obj,
            'media':
            mark_safe(media),
            'inline_admin_formsets':
            inline_admin_formsets,
            'errors':
            helpers.AdminErrorList(form, formsets),
            # 'root_path': self.admin_site.root_path,
            'app_label':
            opts.app_label,
        }
        context.update(reverse_admin_context)
        context.update(extra_context or {})
        return self.render_change_form(
            request,
            context,
            form_url=form_url,
            add=add,
            change=not add,
        )
Ejemplo n.º 21
0
def edit_permissions(modeladmin, request, queryset):
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has the permission to edit permissions
    if not (request.user.is_superuser
            or request.user.has_perm('authority.change_permission')
            or request.user.has_perm('authority.change_foreign_permissions')):
        raise PermissionDenied

    inline = ActionPermissionInline(queryset.model, modeladmin.admin_site)
    formsets = []
    for obj in queryset:
        prefixes = {}
        FormSet = inline.get_formset(request, obj)
        prefix = "%s-%s" % (FormSet.get_default_prefix(), obj.pk)
        prefixes[prefix] = prefixes.get(prefix, 0) + 1
        if prefixes[prefix] != 1:
            prefix = "%s-%s" % (prefix, prefixes[prefix])
        if request.POST.get('post'):
            formset = FormSet(data=request.POST,
                              files=request.FILES,
                              instance=obj,
                              prefix=prefix)
        else:
            formset = FormSet(instance=obj, prefix=prefix)
        formsets.append(formset)

    media = modeladmin.media
    inline_admin_formsets = []
    for formset in formsets:
        fieldsets = list(inline.get_fieldsets(request))
        inline_admin_formset = helpers.InlineAdminFormSet(
            inline, formset, fieldsets)
        inline_admin_formsets.append(inline_admin_formset)
        media = media + inline_admin_formset.media

    ordered_objects = opts.get_ordered_objects()
    if request.POST.get('post'):
        if all_valid(formsets):
            for formset in formsets:
                formset.save()
        else:
            modeladmin.message_user(
                request, '; '.join(err.as_text() for formset in formsets
                                   for err in formset.errors))
        # redirect to full request path to make sure we keep filter
        return HttpResponseRedirect(request.get_full_path())

    context = {
        'errors':
        ActionErrorList(formsets),
        'title':
        ugettext('Permissions for %s') % force_text(opts.verbose_name_plural),
        'inline_admin_formsets':
        inline_admin_formsets,
        'app_label':
        app_label,
        'change':
        True,
        'ordered_objects':
        ordered_objects,
        'form_url':
        mark_safe(''),
        'opts':
        opts,
        'target_opts':
        queryset.model._meta,
        'content_type_id':
        ContentType.objects.get_for_model(queryset.model).id,
        'save_as':
        False,
        'save_on_top':
        False,
        'is_popup':
        False,
        'media':
        mark_safe(media),
        'show_delete':
        False,
        'action_checkbox_name':
        helpers.ACTION_CHECKBOX_NAME,
        'queryset':
        queryset,
        "object_name":
        force_text(opts.verbose_name),
    }
    template_name = getattr(modeladmin, 'permission_change_form_template', [
        "admin/%s/%s/permission_change_form.html" %
        (app_label, opts.object_name.lower()),
        "admin/%s/permission_change_form.html" % app_label,
        "admin/permission_change_form.html"
    ])
    return render_to_response(template_name, context, request)
Ejemplo n.º 22
0
 def render_revision_form(self, request, obj, version, context, revert=False, recover=False):
     """Renders the object revision form."""
     model = self.model
     opts = model._meta
     object_id = obj.pk
     # Generate the model form.
     ModelForm = self.get_form(request, obj)
     formsets = []
     if request.method == "POST":
         # This section is copied directly from the model admin change view
         # method.  Maybe one day there will be a hook for doing this better.
         form = ModelForm(request.POST, request.FILES, instance=obj, initial=self.get_revision_form_data(request, obj, version))
         if form.is_valid():
             form_validated = True
             new_object = self.save_form(request, form, change=True)
             # HACK: If the value of a file field is None, remove the file from the model.
             for field in new_object._meta.fields:
                 if isinstance(field, models.FileField) and field.name in form.cleaned_data and form.cleaned_data[field.name] is None:
                     setattr(new_object, field.name, None)
         else:
             form_validated = False
             new_object = obj
         prefixes = {}
         for FormSet, inline in zip(self.get_formsets(request, new_object),
                                    self.get_inline_instances(request)):
             prefix = FormSet.get_default_prefix()
             prefixes[prefix] = prefixes.get(prefix, 0) + 1
             if prefixes[prefix] != 1:
                 prefix = "%s-%s" % (prefix, prefixes[prefix])
             formset = FormSet(request.POST, request.FILES,
                               instance=new_object, prefix=prefix,
                               queryset=inline.queryset(request))
             self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover)
             # Add this hacked formset to the form.
             formsets.append(formset)
         if all_valid(formsets) and form_validated:
             self.save_model(request, new_object, form, change=True)
             form.save_m2m()
             for formset in formsets:
                 # HACK: If the value of a file field is None, remove the file from the model.
                 related_objects = formset.save(commit=False)
                 for related_obj, related_form in zip(related_objects, formset.saved_forms):
                     for field in related_obj._meta.fields:
                         if isinstance(field, models.FileField) and field.name in related_form.cleaned_data and related_form.cleaned_data[field.name] is None:
                             setattr(related_obj, field.name, None)
                     related_obj.save()
                 formset.save_m2m()
             change_message = _("Reverted to previous version, saved on %(datetime)s") % {"datetime": localize(version.revision.date_created)}
             self.log_change(request, new_object, change_message)
             self.message_user(request, _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": force_text(opts.verbose_name), "name": force_text(obj)})
             # Redirect to the model change form.
             if revert:
                 return HttpResponseRedirect("../../")
             elif recover:
                 return HttpResponseRedirect("../../%s/" % quote(object_id))
             else:
                 assert False
     else:
         # This is a mutated version of the code in the standard model admin
         # change_view.  Once again, a hook for this kind of functionality
         # would be nice.  Unfortunately, it results in doubling the number
         # of queries required to construct the formets.
         form = ModelForm(instance=obj, initial=self.get_revision_form_data(request, obj, version))
         prefixes = {}
         for FormSet, inline in zip(self.get_formsets(request, obj), self.get_inline_instances(request)):
             # This code is standard for creating the formset.
             prefix = FormSet.get_default_prefix()
             prefixes[prefix] = prefixes.get(prefix, 0) + 1
             if prefixes[prefix] != 1:
                 prefix = "%s-%s" % (prefix, prefixes[prefix])
             formset = FormSet(instance=obj, prefix=prefix,
                               queryset=inline.queryset(request))
             self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover)
             # Add this hacked formset to the form.
             formsets.append(formset)
     # Generate admin form helper.
     adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
         self.prepopulated_fields, self.get_readonly_fields(request, obj),
         model_admin=self)
     media = self.media + adminForm.media
     # Generate formset helpers.
     inline_admin_formsets = []
     for inline, formset in zip(self.get_inline_instances(request), formsets):
         fieldsets = list(inline.get_fieldsets(request, obj))
         readonly = list(inline.get_readonly_fields(request, obj))
         prepopulated = inline.get_prepopulated_fields(request, obj)
         inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
             fieldsets, prepopulated, readonly, model_admin=self)
         inline_admin_formsets.append(inline_admin_formset)
         media = media + inline_admin_formset.media
     # Generate the context.
     context.update({"adminform": adminForm,
                     "object_id": object_id,
                     "original": obj,
                     "is_popup": False,
                     "media": mark_safe(media),
                     "inline_admin_formsets": inline_admin_formsets,
                     "errors": helpers.AdminErrorList(form, formsets),
                     "app_label": opts.app_label,
                     "add": False,
                     "change": True,
                     "revert": revert,
                     "recover": recover,
                     "has_add_permission": self.has_add_permission(request),
                     "has_change_permission": self.has_change_permission(request, obj),
                     "has_delete_permission": self.has_delete_permission(request, obj),
                     "has_file_field": True,
                     "has_absolute_url": False,
                     "ordered_objects": opts.get_ordered_objects(),
                     "form_url": mark_safe(request.path),
                     "opts": opts,
                     "content_type_id": ContentType.objects.get_for_model(self.model).id,
                     "save_as": False,
                     "save_on_top": self.save_on_top,
                     "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)),
                     "change_url": reverse("%s:%s_%s_change" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk),)),
                     "history_url": reverse("%s:%s_%s_history" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk),)),
                     "recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name))})
     # Render the form.
     if revert:
         form_template = self.revision_form_template or self._get_template_list("revision_form.html")
     elif recover:
         form_template = self.recover_form_template or self._get_template_list("recover_form.html")
     else:
         assert False
     return render_to_response(form_template, context, template.RequestContext(request))
Ejemplo n.º 23
0
    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta
        if not self.has_add_permission(request):
            raise PermissionDenied

        model_form = self.get_form(request)
        formsets = []
        if request.method == 'POST':
            form = model_form(request.POST, request.FILES)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=False)
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST,
                                  files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix)
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                # Here is the modified code.
                for formset, inline in zip(formsets,
                                           self.get_inline_instances(request)):
                    if not isinstance(inline, ReverseInlineModelAdmin):
                        continue
                    saved = formset.save()
                    if saved:
                        obj = saved[0]
                        setattr(new_object, inline.parent_fk_name, obj)
                self.save_model(request, new_object, form, change=False)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=False)

                #self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = model_form(initial=initial)
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(), prefix=prefix)
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
                                      self.prepopulated_fields)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.get_inline_instances(request),
                                   formsets):
            fieldsets = list(inline.get_fieldsets(request))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline,
                formset,
                fieldsets,
                readonly_fields=inline.readonly_fields)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_text(opts.verbose_name),
            'adminform': adminForm,
            #'is_popup': '_popup' in request.REQUEST,
            'is_popup': False,
            'show_delete': False,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            #'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Ejemplo n.º 24
0
    def add_view(self, request, form_url='', extra_context=None):
        """
        Like the original add_view from ModelAdmin. Alterations are marked
        with 
        # ----start
        # ----end
        """

        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=False)
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet in self.get_formsets(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(
                    data=request.POST,
                    files=request.FILES,
                    instance=new_object,
                    save_as_new=request.POST.has_key("_saveasnew"),
                    prefix=prefix)
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=False)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=False)

                self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)
            prefixes = {}
            for FormSet in self.get_formsets(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(), prefix=prefix)
                formsets.append(formset)

        # --start--
        adminForm = Tabset(form, self.tabs, self.prepopulated_fields)
        # --original--
        # adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)), self.prepopulated_fields)
        # --end--
        media = self.media + adminForm.media

        # --start-- (identical to the one in change_view, except for not passing obj in get_fieldsets)
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline, formset, fieldsets)

            tab = adminForm.get_tab_that_has_inline(inline.__class__.__name__)
            if not tab == None:
                tab.inlines.append(inline_admin_formset)
            else:
                inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        # --original--
        '''
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        '''
        # --end--

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': request.REQUEST.has_key('_popup'),
            'show_delete': False,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Ejemplo n.º 25
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        obj = self.get_object(request, unquote(object_id))

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})

        if request.method == 'POST' and "_saveasnew" in request.POST:
            return self.add_view(request, form_url=reverse('admin:%s_%s_add' %
                                                           (opts.app_label, opts.module_name),
                current_app=self.admin_site.name))

        ModelForm = self.get_form(request, obj)
        formsets = []
        inline_instances = self.get_inline_instances(request, obj)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request, new_object):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST, request.FILES,
                    instance=new_object, prefix=prefix,
                    queryset=inline.get_queryset(request))
                formsets.append(formset)
                if hasattr(inline, 'inlines') and inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

            if self.all_valid_with_nesting(formsets) and form_validated:
                self.save_model(request, new_object, form, True)
                self.save_related(request, form, formsets, True)
                change_message = self.construct_change_message(request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=obj)
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request, obj):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj, prefix=prefix,
                    queryset=inline.get_queryset(request))
                formsets.append(formset)
                if hasattr(inline, 'inlines') and inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
            self.get_prepopulated_fields(request, obj),
            self.get_readonly_fields(request, obj),
            model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            prepopulated = dict(inline.get_prepopulated_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
                fieldsets, prepopulated, readonly, model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if hasattr(inline, 'inlines') and inline.inlines:
                media += self.wrap_nested_inline_formsets(request, inline, formset)

        context = {
            'title': _('Change %s') % force_text(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.GET,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            }
        context.update(extra_context or {})
        return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
Ejemplo n.º 26
0
    def change_view(self, request, object_id, extra_context=None):
        """
        Like the original change_view from ModelAdmin. Alterations are marked
        with 
        # ----start
        # ----end
        """

        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        try:
            obj = self.queryset(request).get(pk=unquote(object_id))
        except model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': force_unicode(opts.verbose_name),
                    'key': escape(object_id)
                })

        if request.method == 'POST' and request.POST.has_key("_saveasnew"):
            return self.add_view(request, form_url='../add/')

        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet in self.get_formsets(request, new_object):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix)
                formsets.append(formset)

            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)

                change_message = self.construct_change_message(
                    request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=obj)
            prefixes = {}
            for FormSet in self.get_formsets(request, obj):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj, prefix=prefix)
                formsets.append(formset)
        # --start--
        adminForm = Tabset(form, self.tabs, self.prepopulated_fields)
        # --original--
        # adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields)
        # --end--
        media = self.media + adminForm.media

        # --start--
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline, formset, fieldsets)

            tab = adminForm.get_tab_that_has_inline(inline.__class__.__name__)
            if not tab == None:
                tab.inlines.append(inline_admin_formset)
            else:
                inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        # --original--
        '''
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            
            media = media + inline_admin_formset.media
        '''
        # --end--

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': request.REQUEST.has_key('_popup'),
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, change=True, obj=obj)
Ejemplo n.º 27
0
    def add_view(self, request, form_url='', extra_context=None):
        """The 'add' admin view for this model."""
        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []

        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)

            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()

            prefixes = {}

            for FormSet, inline in zip(self.get_formsets(request),
                                       self.get_inline_instances(request)):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1

                if prefixes[prefix] != 1:
                    prefix = "{0}-{1}".format(prefix, prefixes[prefix])

                formset = FormSet(data=request.POST, files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix, queryset=inline.queryset(request))

                formsets.append(formset)

                for inline in self.get_inline_instances(request):
                    # If this is the inline that matches this formset, and
                    # we have some nested inlines to deal with, then we need
                    # to get the relevant formset for each of the forms in
                    # the current formset.
                    if inline.inlines and inline.model == formset.model:
                        for nested in inline.inline_instances:
                            for the_form in formset.forms:
                                InlineFormSet = nested.get_formset(request, the_form.instance)
                                prefix = "{0}-{1}".format(the_form.prefix,
                                                          InlineFormSet.get_default_prefix())
                                formsets.append(InlineFormSet(request.POST, request.FILES,
                                                              instance=the_form.instance,
                                                              prefix=prefix))
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=False)
                form.save_m2m()

                for formset in formsets:
                    self.save_formset(request, form, formset, change=False)

                self.log_addition(request, new_object)

                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())

            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue

                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")

            form = ModelForm(initial=initial)
            prefixes = {}

            for FormSet, inline in zip(self.get_formsets(request),
                                       self.get_inline_instances(request)):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1

                if prefixes[prefix] != 1:
                    prefix = "{0}-{1}".format(prefix, prefixes[prefix])

                formset = FormSet(instance=self.model(), prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
                                      self.prepopulated_fields, self.get_readonly_fields(request),
                                      model_admin=self)

        media = self.media + adminForm.media
        inline_admin_formsets = []

        for inline, formset in zip(self.get_inline_instances(request), formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
                                                              fieldsets, readonly,
                                                              model_admin=self)
            if inline.inlines:
                for form in formset.forms:
                    if form.instance.pk:
                        instance = form.instance
                    else:
                        instance = None

                    form.inlines = inline.get_inlines(request, instance, prefix=form.prefix)

                inline_admin_formset.inlines = inline.get_inlines(request)

            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }

        context.update(extra_context or {})

        return self.render_change_form(request, context, form_url=form_url, add=True)
Ejemplo n.º 28
0
    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model. \
         This function has been customized for datetime initial like a ticket #19431"

        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST,
                                  files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=False)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=False)

                self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
                elif isinstance(f, models.DateTimeField):
                    initial[k] = dateutil.parser.parse(initial[k])
            form = ModelForm(initial=initial)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(),
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)

        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Ejemplo n.º 29
0
    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []
        inline_instances = self.get_inline_instances(request, None)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST,
                                  files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix,
                                  queryset=inline.get_queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)
            if self.all_valid_with_nesting(formsets) and form_validated:
                self.save_model(request, new_object, form, False)
                self.save_related(request, form, formsets, False)
                args = ()
                # Provide `add_message` argument to ModelAdmin.log_addition for
                # Django 1.9 and up.
                if VERSION[:2] >= (1, 9):
                    add_message = self.construct_change_message(request,
                                                                form,
                                                                formsets,
                                                                add=True)
                    args = (request, new_object, add_message)
                else:
                    args = (request, new_object)
                self.log_addition(*args)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)
            prefixes = {}
            for FormSet, inline in self.get_formsets_with_inlines(request):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(),
                                  prefix=prefix,
                                  queryset=inline.get_queryset(request))
                formsets.append(formset)
                if hasattr(inline, 'inlines') and inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.get_prepopulated_fields(request),
                                      self.get_readonly_fields(request),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(inline.get_prepopulated_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              prepopulated,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if hasattr(inline, 'inlines') and inline.inlines:
                extra_media = self.wrap_nested_inline_formsets(
                    request, inline, formset)

                if extra_media:
                    media += extra_media

        context = {
            'title': _('Add %s') % force_text(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.GET,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }
        context.update(self.admin_site.each_context(request))
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Ejemplo n.º 30
0
    def add_view(self, request, form_url='', extra_context={}):
        "The 'add' admin view for this model."
        #copied from django/contrib/admin/options.py:924 at version 1.4.0
        model = self.model
        opts = model._meta

        if not self.has_add_permission(request):
            raise PermissionDenied

        ModelForm = self.get_form(request)
        formsets = []
        inline_instances = self.get_inline_instances(request)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST,
                                  files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if hasattr(inline, 'inlines') and inline.inlines:
                    self.add_recursive_inline_formsets(request, inline,
                                                       formset)
            if self.all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, False)
                self.save_related(request, form, formsets, False)
                self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                try:
                    f = opts.get_field(k)
                except FieldDoesNotExist:
                    continue
                if isinstance(f, ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(),
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if hasattr(inline, 'inlines'):
                    self.add_recursive_inline_formsets(request, inline,
                                                       formset)

        adminForm = helpers.AdminForm(form,
                                      list(self.get_fieldsets(request)),
                                      self.get_prepopulated_fields(request),
                                      self.get_readonly_fields(request),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(inline.get_prepopulated_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              prepopulated,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if hasattr(inline, 'inlines'):
                media = media + self.wrap_recursive_inline_formsets(
                    request, inline, formset)

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)