Example #1
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_unicode(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(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.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, 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(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.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = 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 = InlineAdminFormSet(inline, formset,
                fieldsets, prepopulated, readonly, model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(request, inline, formset)

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.POST,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            'django_version_lt_1_6': DJANGO_VERSION < (1, 6)
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
Example #2
0
def show_general_information(request, gen_info_id, action=None):
    gi, edit_enabled, type_of_assessment, gi_json, slug_name = (
        _general_information_serialize(request, gen_info_id))

    curve_in_cart = gi.cart.filter(username=request.user.username)
    cart_curves = GeneralInformation.objects.filter(
        cart__username=request.user.username)
    from_page = request.POST.get("from", "list")
    from_page_info = (
        "back to list of all curves" if from_page == "list" else
        "back to curves collection exportable as single NRML file")
    other_page = ("cart" if from_page == "list" else "list")
    other_page_info = ("go to curves collection exportable as single NRML file"
                       if from_page == "list" else "go to list of all curves")
    if request.method == 'POST':  # If the form has been submitted...
        user = User.objects.get(username=request.user.username)

        failed = False
        if action == 'add-to-cart':
            # check consistency with first curve stored
            while True:
                if curve_in_cart:
                    messages.error(
                        request,
                        'Curve "%s" already in cart.' % force_unicode(gi.name))
                    failed = True
                    break

                first_in_cart = GeneralInformation.objects.filter(cart=user)

                if first_in_cart:
                    first_in_cart = first_in_cart[0]
                    gi_first = GeneralInformation.objects.select_related().get(
                        pk=first_in_cart.id)

                    # check curve type
                    if gi_first.type_of_assessment != gi.type_of_assessment:
                        types_of_assessment = dict(TYPES_OF_ASSESSMENT)
                        messages.error(
                            request,
                            'Curve "type of assessment" is "%s" but '
                            'must be "%s" to be '
                            'added to the current cart.'
                            % (types_of_assessment[gi.type_of_assessment],
                               types_of_assessment[
                                   gi_first.type_of_assessment]))
                        failed = True
                        break

                    # check curve category
                    categories = dict(CATEGORIES)
                    if ((gi_first.category <= CAT.STR_CLASS and
                         gi.category > CAT.STR_CLASS) or
                        (gi_first.category > CAT.STR_CLASS and
                         gi_first.category != gi.category)):
                        messages.error(
                            request,
                            'Curve "category" is "%s" but must be "%s" to be '
                            'added to the current cart.'
                            % (categories[gi.category],
                               (('%s" or "%s' % (categories[CAT.STR_SPEC],
                                                 categories[CAT.STR_CLASS]))
                                if gi_first.category <= CAT.STR_CLASS
                                else categories[gi_first.category])))
                        failed = True
                        break

                    # additional checks if type_of_assessment is TA.FRAGILITY
                    if gi_first.type_of_assessment == TA.FRAGILITY:
                        if (gi_first.fragility_func.limit_states_num !=
                                gi.fragility_func.limit_states_num):
                            messages.error(
                                request,
                                'Curve "limit states" are %d '
                                'but must be %d to be '
                                'added to the current cart.' %
                                (gi.fragility_func.limit_states_num,
                                 gi_first.fragility_func.limit_states_num))
                            failed = True
                            break

                        if (gi_first.fragility_func.func_distr_type !=
                                gi.fragility_func.func_distr_type):
                            fdt = gi_first.fragility_func.func_distr_type
                            messages.error(
                                request,
                                ('All curves added to the current cart must '
                                 'be a fragility curve and must be %s type.' %
                                 dict(FUNC_DISTR_TYPES)[fdt].lower()))
                            failed = True
                            break

                        if (gi_first.fragility_func.limit_states_desc !=
                                gi.fragility_func.limit_states_desc):
                            messages.warning(
                                request,
                                'Curve limit states description "%s" differs '
                                'from first curve in the cart "%s"' %
                                (gi.fragility_func.limit_states_desc,
                                 gi_first.fragility_func.limit_states_desc))
                break

            if not curve_in_cart and not failed:
                gi.cart.add(user)
                # curve_in_cart should be '[ gi ]' to be consistent with the
                # rest of the code but from here we are interested in
                # if is None or not None.
                curve_in_cart = True
                messages.add_message(
                    request, messages.INFO,
                    'Curve ' + force_unicode(gi.name) + ' added to collection'
                    ' of curves to export as a single NRML file.')
            return redirect('view', gen_info_id=gen_info_id)
        elif action == 'remove-from-cart':
            if curve_in_cart:
                gi.cart.remove(user)
                messages.add_message(
                    request,
                    messages.INFO,
                    'Curve ' + force_unicode(gi.name) + ' removed from'
                    ' collection of curves to export as a single NRML file')
                curve_in_cart = None
            else:
                messages.add_message(
                    request,
                    messages.ERROR,
                    'Curve ' + force_unicode(gi.name) + ' not in collection'
                    ' of curves to export as a single NRML file.')
            return redirect('view', gen_info_id=gen_info_id)
        elif action == 'export-as-nrml':
            return _func_export_as_nrml(request, gen_info_id)

    return render_to_response(
        'vulnerability/show_general_information.html',
        dict(general_information=json.dumps(gi_json),
             page_title=gi.name,
             from_page=from_page,
             from_page_info=from_page_info,
             other_page=other_page,
             other_page_info=other_page_info,
             type_of_assessment=type_of_assessment,
             curve_id=gen_info_id,
             edit_enabled=edit_enabled,
             curve_in_cart=curve_in_cart,
             cart_curves=cart_curves,
             slug_name=slug_name,
             user_mailaddr="%s %s <%s>" % (
                    gi.owner.first_name, gi.owner.last_name,
                    gi.owner.email),
             vuln_mailaddr="GEM Vulnerability Team <*****@*****.**>",
             vuln_mailsubj="Vulnerability: question about %s" % gi.name),
        context_instance=RequestContext(request))
Example #3
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(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.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)

                if DJANGO_VERSION < (1, 9):
                    change_message = self.construct_change_message(request, form, formsets)
                    self.log_addition(request, new_object)
                else:
                    change_message = self.construct_change_message(request, form, formsets, True)
                    self.log_addition(request, new_object, change_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(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.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = 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 = InlineAdminFormSet(inline, formset,
                fieldsets, prepopulated, readonly, model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(request, inline, formset)

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.POST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            'django_version_lt_1_6': DJANGO_VERSION < (1, 6)
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, form_url=form_url, add=True)
Example #4
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_unicode(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(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 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(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 inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = 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 = InlineAdminFormSet(inline,
                                                      formset,
                                                      fieldsets,
                                                      prepopulated,
                                                      readonly,
                                                      model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(
                    request, inline, formset)

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.POST,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            'django_version_lt_1_6': DJANGO_VERSION < (1, 6)
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       change=True,
                                       obj=obj,
                                       form_url=form_url)
Example #5
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(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)

                if DJANGO_VERSION < (1, 9):
                    change_message = self.construct_change_message(
                        request, form, formsets)
                    self.log_addition(request, new_object)
                else:
                    change_message = self.construct_change_message(
                        request, form, formsets, True)
                    self.log_addition(request, new_object, change_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(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 inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = 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 = InlineAdminFormSet(inline,
                                                      formset,
                                                      fieldsets,
                                                      prepopulated,
                                                      readonly,
                                                      model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(
                    request, inline, formset)

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.POST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            'django_version_lt_1_6': DJANGO_VERSION < (1, 6)
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Example #6
0
    def delete_view(self, request, object_id, extra_context=None):
        "The 'delete' admin view for this model."
        opts = self.model._meta
        app_label = opts.app_label

        obj = self.get_object(request, unquote(object_id))
        type_of_assessment = obj.type_of_assessment
        if not self.has_delete_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)})

        using = router.db_for_write(self.model)

        # Populate deleted_objects, a data structure of all related objects
        # that will also be deleted.
        (deleted_objects, perms_needed, protected) = get_deleted_objects(
            [obj], opts, request.user, self.admin_site, using)

        if request.POST:  # The user has already confirmed the deletion.
            if perms_needed:
                raise PermissionDenied
            obj_display = force_unicode(obj)
            self.log_deletion(request, obj, obj_display)
            self.delete_model(request, obj)

            self.message_user(
                request,
                _('The %(name)s "%(obj)s" was deleted successfully.') % {
                    'name': force_unicode(opts.verbose_name),
                    'obj': force_unicode(obj_display)})

            if not self.has_change_permission(request, None):
                return HttpResponseRedirect(
                    reverse('admin:index',
                            current_app=self.admin_site.name))
            post_url = "/vulnerability/list/?type_of_assessment=%d" % (
                type_of_assessment)

            return HttpResponseRedirect(post_url)

        object_name = force_unicode(opts.verbose_name)

        if perms_needed or protected:
            title = _("Cannot delete %(name)s") % {"name": object_name}
        else:
            title = _("Are you sure?")

        context = {
            "title": title,
            "object_name": object_name,
            "object": obj,
            "deleted_objects": deleted_objects,
            "perms_lacking": perms_needed,
            "protected": protected,
            "opts": opts,
            "app_label": app_label,
        }
        context.update(extra_context or {})

        return TemplateResponse(request, self.delete_confirmation_template or [
            "admin/%s/%s/delete_confirmation.html" % (
                app_label, opts.object_name.lower()),
            "admin/%s/delete_confirmation.html" % app_label,
            "admin/delete_confirmation.html"
        ], context, current_app=self.admin_site.name)
Example #7
0
    def clone_view(self, request, object_id, extra_context=None):
        # This method is a cut and paste copy of ModelAdmin.change_view with
        # a custom form instead of the admin form. It allows editing the base
        # properties of the AccessPoint, and creates a copy upon saving

        ## Access control performed as ModelAdmin.change_view
        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)})

        formsets = []

        if request.method == "POST":
            form = myforms.APForm(request.POST)
            if form.is_valid():
                newobj = form.save(commit=False)
                # Remove the id, we want a new one
                newobj.id = None
                newobj.save(force_insert=True)

                # Copy related parameters
                for apparam in obj.apparameter_set.all():
                    # Remove the id, we want a new one
                    apparam.id = None
                    apparam.ap = newobj
                    apparam.save(force_insert=True)

                # Copy related protocol support
                for psup in obj.protocol_support.all():
                    #Remove the id, we want a enw one
                    psup.id = None
                    psup.ap = newobj
                    psup.save(force_insert=True)

                msg = _('The %(name)s "%(obj)s" was cloned successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
                # Add new, go back or edit
                if request.POST.has_key("_addanother"):
                    self.message_user(request, msg + ' ' + _("You may clone it again below."))
                    return HttpResponseRedirect("../clone/")
                elif request.POST.has_key("_continue"):
                    self.message_user(request, msg + ' ' + _("You may edit it below."))
                    return HttpResponseRedirect("../../%s/" % newobj._get_pk_val())
                else:
                    self.message_user(request, msg)
                    return HttpResponseRedirect("../../")

        else:
            form = myforms.APForm(instance=obj)

            ## Setup formsets (change_form)
            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 = []

        context = {
            'title': _('Clone %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 {})
        with nested(
            temp_setattr(self, "change_form_template", [
                "admin/%s/%s/clone_form.html" % (opts.app_label, opts.object_name.lower()),
                "admin/%s/clone_form.html" % (opts.app_label),
                "admin/clone_form.html",
                ])
            ):
            return self.render_change_form(request, context, change=True, obj=obj)
Example #8
0
    def init_parameters_view(self, request, object_id, extra_context=None):
        ## Access control performed as ModelAdmin.change_view
        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)})

        show_trace = request.GET.get("show_trace", "no") == "yes"
        limit = request.GET.get("limit", None) is not None

        limit_params = None
        if limit:
            tracer = models.ParamTracer()
            ctx = Context({"ap":obj, tracer.tracer_key:tracer})
            for init_section in obj.architecture.initsection_set.order_by('section__name'):
                init_section.compile_template().render(ctx)
            limit_params = tracer.params.keys()

        full_param_info = obj.get_full_param_information()

        return render_to_response("admin/accesspoints/accesspoint/init_parameters.html",
            {
                "app_label":opts.app_label,
                "original":obj,
                "opts":opts,
                "parameters":self.param_iterator(full_param_info, limit_params),
                "full":show_trace,
                "title":_(u"Parameters Overview"),
            },
            context_instance=RequestContext(request),
            )