Пример #1
0
def sync_from_production(modeladmin, request):
    model_cls = modeladmin.model
    adapter = get_adapter(model_cls)
    db_conn = adapter.conn_ops['db'](settings.MONGODB_CONF)

    start_time = get_last_sync_timestamp(model_cls)
    need_sync_items = getattr(db_conn, adapter.conn_ops['method'])(start_time)
    for item in need_sync_items:
        to_model = adapter.convert_from(model_cls(), item)
        to_model.save()
    count = len(need_sync_items)
    if count:
        modeladmin.message_user(
            request,
            _("%(count)d %(items)s successfully sync data from production environment."
              ) % {
                  'count': count,
                  'items': model_ngettext(modeladmin.opts, count)
              })
    else:
        modeladmin.message_user(
            request,
            _("No %(items)s need to sync to production environment.") % {
                'items': model_ngettext(modeladmin.opts, count),
            })
Пример #2
0
    def really_delete_selected(self, request, queryset):
        deleted_count = 0
        protected_count = 0

        # Check that the user has delete permission for the actual model
        if not self.has_delete_permission(request):
            raise PermissionDenied

        for obj in queryset:
            try:
                obj.delete()
                deleted_count += 1
            except ProtectedError:
                protected_count += 1

        if deleted_count:
            messages.add_message(request, messages.INFO, _("Successfully deleted %(count)d %(items)s.") % {
                "count": deleted_count, "items": model_ngettext(self.opts, deleted_count)
            })

        if protected_count:
            # TODO More informative feedback, possibly with an intermediate screen. Compare messages on trying to delete one object.
            messages.add_message(request, messages.ERROR, _("%(count)d %(items)s not deleted, because that would require deleting protected related objects.") % {
                "count": protected_count, "items": model_ngettext(self.opts, protected_count)
            })
Пример #3
0
    def really_delete_selected(self, request, queryset):
        deleted_count = 0
        protected_count = 0

        # Check that the user has delete permission for the actual model
        if not self.has_delete_permission(request):
            raise PermissionDenied

        for obj in queryset:
            try:
                obj.delete()
                deleted_count += 1
            except ProtectedError:
                protected_count += 1

        if deleted_count:
            messages.add_message(
                request, messages.INFO,
                _("Successfully deleted %(count)d %(items)s.") % {
                    "count": deleted_count,
                    "items": model_ngettext(self.opts, deleted_count)
                })

        if protected_count:
            # TODO More informative feedback, possibly with an intermediate screen. Compare messages on trying to delete one object.
            messages.add_message(
                request, messages.ERROR,
                _("%(count)d %(items)s not deleted, because that would require deleting protected related objects."
                  ) % {
                      "count": protected_count,
                      "items": model_ngettext(self.opts, protected_count)
                  })
Пример #4
0
def sync_to_production(modeladmin, request=None):
    adapter = get_adapter(modeladmin.model)
    db_conn = adapter.conn_ops['db'](settings.MONGODB_CONF)
    update_table = adapter.conn_ops['table']

    if request:
        need_sync_items = modeladmin.queryset(request).filter(sync_status=0)
    else:
        need_sync_items = modeladmin.model.objects.filter(sync_status=0)
    sync_successed = 0
    sync_failed = 0
    for i, obj in enumerate(need_sync_items):
        can_upsert = obj.published and not obj.hided
        to_obj = {}
        try:
            to_obj = adapter.convert_to(obj)
            if not to_obj:
                msg = 'convert to failed %s, id: %s' % (modeladmin.model,
                                                        obj.pk)
                logger.warn(msg)
                sync_failed += 1
            else:
                cond = {
                    'pk': to_obj['pk']
                } if 'pk' in to_obj else {
                    'id': to_obj['id']
                }
                if can_upsert:
                    db_conn.upsert_item(update_table,
                                        cond,
                                        to_obj,
                                        upsert=True)
                else:
                    db_conn.delete_item(update_table, cond)
                obj.sync_status = 1
                obj.save()
                sync_successed += 1
        except Exception:
            msg = 'sync failed %s, id: %s' % (modeladmin.model, obj.pk)
            logger.exception(msg)
            sync_failed += 1

    success_msg = _(
        "%(count)d %(items)s successfully sync data to production environment.\n"
    ) % {
        'count': sync_successed,
        'items': model_ngettext(modeladmin.opts, sync_successed)
    }
    failed_msg = _(
        "%(count)d %(items)s fail sync data to production environment.\n") % {
            'count': sync_failed,
            'items': model_ngettext(modeladmin.opts, sync_failed)
        }
    if request:
        modeladmin.message_user(request, success_msg + failed_msg)
    else:
        print success_msg + failed_msg
Пример #5
0
    def undelete_selected(self, request, queryset):
        """
        Action which undeletes the selected objects.

        This action first displays a confirmation page whichs shows all the
        undeleteable objects, or, if the user has no permission a "permission
        denied" message.

        Next, it undelets all selected objects and redirects back to the
        change list.
        """
        opts = self.model._meta
        app_label = opts.app_label

        # Check that the user has undelete permission for the actual model
        if not self.has_undelete_permission(request):
            raise PermissionDenied

        undeletable_objects = queryset.only_deleted()
        count = undeletable_objects.count()
        if count == 0:
            messages.error(request, _("No objects for undelete."))
            return None

        # The user has already confirmed the undeletion.
        # Do the undeletion and return a None to display the change list view again.
        if request.POST.get('post'):
            for obj in undeletable_objects:
                obj_display = force_unicode(obj)
                self.log_change(request, obj, _("Undeleted %s") % obj_display)
            undeletable_objects.undelete()
            self.message_user(request, _("Successfully undeleted %(count)d %(items)s.") % {
                "count": count, "items": model_ngettext(self.opts, count)
            })
            # Return None to display the change list page again.
            return None

        context = {
            "title": _("Are you sure?"),
            "objects_name": force_unicode(model_ngettext(self.opts, count)),
            "undeletable_objects": [undeletable_objects],
            "queryset": queryset,
            "opts": opts,
            "app_label": app_label,
            'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
            }

        # Display the confirmation page
        return TemplateResponse(request, self.undelete_selected_confirmation_template or [
            "admin/%s/%s/undelete_selected_confirmation.html" % (app_label, opts.module_name),
            "admin/%s/undelete_selected_confirmation.html" % app_label,
            "admin/undelete_selected_confirmation.html"
        ], context, current_app=self.admin_site.name)
Пример #6
0
def duplicate_object(modeladmin, request, queryset):
    rows = [obj.clone() for obj in queryset]
    msg = _("Successfully duplicated %(count)d %(items)s") % {
        'count': len(rows),
        'items': model_ngettext(modeladmin.opts, rows)
    }
    modeladmin.message_user(request, msg)
Пример #7
0
def make_rubrics_by_publications_attributes(modeladmin, request, queryset):
    """
    Make sub rubrics structure by additional publications attributes.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label
    error_message = None

    # Check that the user has delete and change permission for the actual model
    if not (modeladmin.has_delete_permission(request) and modeladmin.has_change_permission(request)):
        raise PermissionDenied

    def format_callback(obj):
        opts = obj._meta
        admin_url = reverse('%s:%s_%s_change'
                            % (modeladmin.admin_site.name,
                               opts.app_label,
                               opts.object_name.lower()),
                            None, (quote(obj._get_pk_val()),))
        # Display a link to the admin page.
        return mark_safe(u'%s: <a href="%s">%s</a>' %
                         (escape(capfirst(opts.verbose_name)),
                          admin_url,
                          escape(obj)))
    to_proceed = []
    for obj in queryset:
        to_proceed.append(format_callback(obj))

    if request.POST.get('post'):
        form = MakeRubricsByPublicationsAttributesAdminForm(request.POST)
        if form.is_valid():
            n = queryset.count()
            if n:
                try:
                    for target_rubric in queryset:
                        call_command('make_rubrics_by_publications_attributes', target_id=target_rubric.id)
                        #target_rubric_display = force_unicode(target_rubric)
                        #modeladmin.log_change(request, target_rubric, target_rubric_display)
                    modeladmin.message_user(request, _("Successfully proceed %(count)d %(items)s.") % {
                        "count": n, "items": model_ngettext(modeladmin.opts, n)
                    })
                    return None
                except CommandError as e:
                    error_message = force_unicode(e)
    else:
        form = MakeRubricsByPublicationsAttributesAdminForm()

    context = {
        "title": _("Making sub rubrics structure by additional publications attributes"),
        'form': form,
        "objects_name": force_unicode(opts.verbose_name) if len(queryset) else force_unicode(opts.verbose_name_plural),
        "to_proceed": [to_proceed],
        'queryset': queryset,
        "opts": opts,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'error_message': error_message,
    }
    return TemplateResponse(request, "publication_backbone/admin/actions/make_rubrics_by_publications_attibutes.html",
                            context, current_app=modeladmin.admin_site.name)
Пример #8
0
	def uninstall_form(self, request, queryset):
		"""
			The delete view for this model.
		"""
		opts = self.model._meta
		app_label = opts.app_label

		# Check that the user has delete permission for the actual model
		if not self.has_delete_permission(request):
			raise PermissionDenied

		# Populate deletable_objects, a data structure of all related objects that
		# will also be deleted.
		deletable_objects, perms_needed = get_deleted_objects(queryset, opts, request.user, self.admin_site, levels_to_root=2)
		# The user has already confirmed the deletion.
		# Do the deletion and return a None to display the change list view again.
		if request.method == 'POST':
			if perms_needed:
				raise PermissionDenied
			n = queryset.count()
			if n:
				for obj in queryset:
					obj_display = force_unicode(obj)
					self.log_deletion(request, obj, obj_display)
					obj.delete()
				self.message_user(request, _("Desinstalados com sucesso: %(count)d %(items)s.") % {
					"count": n, "items": model_ngettext(self.opts, n)
				})
		return None
Пример #9
0
def fh_cancel_audit(modeladmin, request, queryset):
    """
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label
    
    # Populate modifiable_objects, a data structure of all related objects that will also be deleted.
    modifiable_objects, perms_needed = get_deleted_objects(queryset, opts, request.user, modeladmin.admin_site, levels_to_root=2)
    
    can_audit = validate_false_paper_have_type(queryset, [enums.FW_PAPER_TYPE, enums.BMW_PAPER_TYPE])
    if can_audit == False:
        messages.error(request, msg_paper_not_belong_fht)
        return None
    paper_st_right = validate_false_paper_status(request, queryset, [enums.PAPER_STATUS_FINISH], u'独立复核团队取消终审')
    if paper_st_right == False:
        return None
    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.    
    if request.POST.get('post'):
        user = request.user
        # 权限判定
        if not has_fh_end_audit_perm(user) and not has_manage_perm(user):
            raise PermissionDenied
        
        n = queryset.count()
        if n:
            for obj in queryset :
                obj_display = force_unicode(obj)
                #remove paper FW audit info
                audits = PaperAudit.objects.filter(paper=obj, new_status=obj.status)
                for au in audits:
                    au.delete()
                    
                obj.status = enums.FH_PAPER_STATUS_WAIT_AUDIT_2
                obj.save()
                
                # change
                modeladmin.log_change(request, obj, obj_display)

            modeladmin.message_user(request, u'成功 取消 %(count)d %(items)s 复核终审.' % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
        
        # Return None to display the change list page again.
        return None
    
    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        "modifiable_objects": modifiable_objects,
        'queryset': queryset,
        
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }
    
    # Display the confirmation page
    return render_to_response('fh_cancel_audit_confirmation.html', context, context_instance=template.RequestContext(request))
Пример #10
0
def send_newsletter_issue(modeladmin, request, queryset):
    """
    Ask the user to confirm their intent to send a newsletter issue
    before continuing. Based on the delete_selected action from the Django admin.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    if request.POST.get('post'):
        # Do send
        for issue in queryset:
            issue.send()

        # Notify user
        n = queryset.count()
        modeladmin.message_user(request,
                _("Successfully sent %(count)d %(newsletters)s.") % {
                        'count': n,
                        'newsletters': model_ngettext(modeladmin.opts, n)
                    })

        # Return None to display the change list page again
        return None

    context = {
        'title': _('Are you sure?'),
        'object_name': force_unicode(opts.verbose_name),
        'queryset': queryset,
        'opts': opts,
        'app_label': app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    return render_to_response('nova/admin/send_selected_confirmation.html',
            context, context_instance=template.RequestContext(request))
Пример #11
0
def unpublish_selected(modeladmin, request, queryset):
    opts = modeladmin.model._meta
    app_label = opts.app_label

    if request.POST.get('post'):
        n = queryset.count()
        if n:
            queryset.unpublish()
            modeladmin.message_user(request, _("Successfully unpublished %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
            # Return None to display the change list page again.
            return None
    
    admin_site = modeladmin.admin_site
 
    context = {
        "title": _("Publish?"),
        "object_name": force_unicode(opts.verbose_name),
        'queryset': queryset,
        "opts": opts,
        "root_path": _root_path(admin_site),
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(modeladmin.publish_confirmation_template or [
        "admin/%s/%s/unpublish_selected_confirmation.html" % (app_label, opts.object_name.lower()),
        "admin/%s/unpublish_selected_confirmation.html" % app_label,
        "admin/unpublish_selected_confirmation.html"
    ], context, context_instance=template.RequestContext(request))
Пример #12
0
    def sync_selected_items(self, request, queryset):
        n = queryset.count()
        fails = []
        reasons = ''
        if n:
            for obj in queryset:
                status, reasons = sync_obj(obj, self.model)
                if not status:
                    fails.append(obj)
            synced_count = n - len(fails)
            self.message_user(request, _('Successfully synced %(count)d %(items)s.') % {
                'count': synced_count, 'items': model_ngettext(self.opts, synced_count)
            }, level=messages.SUCCESS)
        else:
            self.message_user(request, _('0 items synced, Please check sync status.'), level=messages.WARNING)

        if fails:
            fails_count = len(fails)
            ids = ','.join([str(o.id) for o in fails])
            self.message_user(request, _('%(count)d  items fail to sync, id:[%(items)s]') % {
                'count': fails_count,
                'items': ids
            },
                level=messages.ERROR
            )
            if reasons:
                self.message_user(request, _('Fail reasons: %(reasons)s') % {
                    'reasons': reasons,
                },
                    level=messages.ERROR
                )
Пример #13
0
def delete_selected(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    deletable_objects, perms_needed = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, using)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = queryset.count()
        if n:
            for obj in queryset:
                obj_display = force_unicode(obj)
                modeladmin.log_deletion(request, obj, obj_display)
            queryset.delete()
            modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
        # Return None to display the change list page again.
        return None

    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        "deletable_objects": [deletable_objects],
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(modeladmin.delete_selected_confirmation_template or [
        "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()),
        "admin/%s/delete_selected_confirmation.html" % app_label,
        "admin/delete_selected_confirmation.html"
    ], context, context_instance=template.RequestContext(request))
Пример #14
0
 def deactivate(self, request, queryset):
     for entry in queryset:
         entry.is_active = False
         entry.save()
     n = queryset.count()
     self.message_user(request, _("Successfully deactivated %(count)d %(items)s.") % {
         "count": n, "items": model_ngettext(self.opts, n)
     })
Пример #15
0
 def sync_selected_items(self, request, queryset):
     n = queryset.count()
     if n:
         for obj in queryset:
             sync_obj(obj, self.model)
         self.message_user(request, _('Successfully synced %(count)d %(items)s.') % {
             'count': n, 'items': model_ngettext(self.opts, n)
         })
Пример #16
0
    def really_delete_selected(self, request, queryset):
        for obj in queryset:
            obj.delete()

        n = queryset.count()
        self.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
            "count": n, "items": model_ngettext(self.opts, n)
        })
Пример #17
0
def make_disabled(modeladmin, request, queryset):
    objs = queryset.update(logical_exclude=True)
    rows = objs
    msg = _("Successfully disabled %(count)d %(items)s.") % {
        "count": rows,
        "items": model_ngettext(modeladmin.opts, rows)
    }
    modeladmin.message_user(request, msg)
Пример #18
0
def categorize_selected(modeladmin, request, queryset):
    """
    Action which categorizes the selected objects.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    using = router.db_for_write(modeladmin.model)

    # Do the categorization and return a None to display the change list view again.
    if request.POST.get('post'):
        categories = Category.objects.filter(
            pk__in=request.POST.getlist("categories"))
        n = queryset.count()
        if n:
            for obj in queryset:
                old_categories = [
                    categzt.category for categzt in obj.categories.all()
                ]
                for cat in categories:
                    if not cat in old_categories:
                        Categorization(content_object=obj, category=cat).save()
            modeladmin.message_user(
                request,
                _("Successfully categorized %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                })
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_unicode(opts.verbose_name)
    else:
        objects_name = force_unicode(opts.verbose_name_plural)

    title = _("Categorize selected objects")
    ct = ContentType.objects.get_for_model(queryset[0])
    collections = ct.collection_set.all()

    context = {
        "title": title,
        "objects_name": objects_name,
        "collections": collections,
        'queryset': queryset,
        "opts": opts,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return TemplateResponse(
        request,
        modeladmin.delete_selected_confirmation_template
        or ["admin/categorize_selected_choose_category.html"],
        context,
        current_app=modeladmin.admin_site.name)
Пример #19
0
def publish_selected(modeladmin, request, queryset):
    queryset = queryset.select_for_update()
    opts = modeladmin.model._meta
    app_label = opts.app_label

    all_published = NestedSet()
    for obj in queryset:
        obj.publish(dry_run=True, all_published=all_published)

    perms_needed = []
    _check_permissions(modeladmin, all_published, request, perms_needed)

    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied

        n = queryset.count()
        if n:
            for object in all_published:
                modeladmin.log_publication(request, object)

            queryset.publish()

            modeladmin.message_user(
                request,
                _("Successfully published %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                })
            # Return None to display the change list page again.
            return None

    admin_site = modeladmin.admin_site

    context = {
        "title": _("Publish?"),
        "object_name": force_unicode(opts.verbose_name),
        "all_published":
        _convert_all_published_to_html(admin_site, all_published),
        "perms_lacking": _to_html(admin_site, perms_needed),
        'queryset': queryset,
        "opts": opts,
        "root_path": _root_path(admin_site),
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(
        modeladmin.publish_confirmation_template or [
            "admin/%s/%s/publish_selected_confirmation.html" %
            (app_label, opts.object_name.lower()),
            "admin/%s/publish_selected_confirmation.html" % app_label,
            "admin/publish_selected_confirmation.html"
        ],
        context,
        context_instance=template.RequestContext(request))
Пример #20
0
def gen_report_bentch(modeladmin, request, queryset):
    """
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label
    
    # Populate modifiable_objects, a data structure of all related objects that will also be deleted.
    modifiable_objects, perms_needed = get_deleted_objects(queryset, opts, request.user, modeladmin.admin_site, levels_to_root=2)

#    can_audit = validate_false_paper_have_type(queryset, [enums.BMW_PAPER_TYPE, enums.FH_PAPER_TYPE])
#    if can_audit == False:
#        messages.error(request, u'FW团队终审问卷才能生成单店报告')
#        return None
    
    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.    
    if request.POST.get('post'):
        user = request.user
        # 权限判定
        #督导,终审,管理员可用
        if not has_fh_end_audit_perm(user) and not has_end_audit_perm(user) and not has_manage_perm(user) and not has_dd_audit_perm(user):
            raise PermissionDenied
        
        n = queryset.count()
        if n:
            from mc import gen_report
            perm = enums.PAPER_STATUS_FINISH
            for obj in queryset :
                if obj.status == perm:
                    obj_display = force_unicode(obj)
                    #统计得
                    gen_report(obj, user)
                    # change
                    modeladmin.log_change(request, obj, obj_display)
                else:
                    n -= 1
            modeladmin.message_user(request, u'生成 %(count)d %(items)s EXCEL单店报告.' % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
        
        # Return None to display the change list page again.
        return None
    
    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        "modifiable_objects": modifiable_objects,
        'queryset': queryset,
        
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }
    
    # Display the confirmation page
    return render_to_response('gen_report_bentch_confirmation.html', context, context_instance=template.RequestContext(request))
Пример #21
0
 def delete_selected_items(self, request, queryset):
     n = queryset.count()
     if n:
         for obj in queryset:
             self.log_deletion(request, obj, force_unicode(obj))
             obj.delete()
         self.message_user(request, _('Successfully deleted %(count)d %(items)s.') % {
             'count': n, 'items': model_ngettext(self.opts, n)
         })
Пример #22
0
def sync_to_production(modeladmin, request=None):
    adapter = get_adapter(modeladmin.model)
    db_conn = adapter.conn_ops['db'](settings.MONGODB_CONF)
    update_table = adapter.conn_ops['table']

    need_sync_items = (modeladmin.queryset(request) if request else modeladmin.model.objects).filter(sync_status=0)
    sync_successed, sync_failed = 0, 0

    for i, obj in enumerate(need_sync_items):
        can_upsert = obj.published and not obj.hided
        to_obj = {}

        try:
            to_obj = adapter.convert_to(obj)
            if not to_obj:
                msg = 'convert to failed %s, id: %s' % (modeladmin.model, obj.pk)
                logger.warn(msg)
                sync_failed += 1
            else:
                cond = {'pk': to_obj['pk']} if 'pk' in to_obj else {'id': to_obj['id']}
                if can_upsert:
                    db_conn.upsert_item(update_table, cond, to_obj, upsert=True)
                else:
                    db_conn.delete_item(update_table, cond)
                obj.sync_status = 1
                obj.save()
                sync_successed += 1
        except Exception:
            msg = 'sync failed %s, id: %s' % (modeladmin.model, obj.pk)
            logger.exception(msg)
            sync_failed += 1

    success_msg = _("%(count)d %(items)s successfully sync data to production environment.\n") % {
        'count': sync_successed,
        'items': model_ngettext(modeladmin.opts, sync_successed)
    }
    failed_msg = _("%(count)d %(items)s fail sync data to production environment.\n") % {
        'count': sync_failed,
        'items': model_ngettext(modeladmin.opts, sync_failed)
    }
    if request:
        modeladmin.message_user(request, success_msg + failed_msg)
    else:
        print success_msg + failed_msg
Пример #23
0
def delete_selected(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    deletable_objects, perms_needed = get_deleted_objects(queryset, opts, request.user, modeladmin.admin_site)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = queryset.count()
        if n:
            for obj in queryset:
                obj_display = force_unicode(obj)
                modeladmin.log_deletion(request, obj, obj_display)
            queryset.delete()
            modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
        # Return None to display the change list page again.
        return None

    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        "deletable_objects": [deletable_objects],
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(modeladmin.delete_selected_confirmation_template or [
        "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()),
        "admin/%s/delete_selected_confirmation.html" % app_label,
        "admin/delete_selected_confirmation.html"
    ], context, context_instance=template.RequestContext(request))
Пример #24
0
def sync_from_production(modeladmin, request):
    model_cls = modeladmin.model
    adapter = get_adapter(model_cls)
    db_conn = adapter.conn_ops['db'](settings.MONGODB_CONF)

    start_time = get_last_sync_timestamp(model_cls)
    need_sync_items = getattr(db_conn, adapter.conn_ops['method'])(start_time)
    for item in need_sync_items:
        to_model = adapter.convert_from(model_cls(), item)
        to_model.save()
    count = len(need_sync_items)
    if count:
        modeladmin.message_user(request, _("%(count)d %(items)s successfully sync data from production environment.") % {
            'count': count, 'items': model_ngettext(modeladmin.opts, count)
        })
    else:
        modeladmin.message_user(request, _("No %(items)s need to sync to production environment.") % {
            'items': model_ngettext(modeladmin.opts, count),
        })
Пример #25
0
    def form_valid(self, form):
        objects = form.bulk_create(Place)

        if self.model_admin:
            n = len(objects)
            self.model_admin.message_user(
                self.request,
                _("Successfully inserted {count:d} {items}.").format(
                    count=n, items=model_ngettext(self.model_admin.opts, n)))

        return super(BulkUploadFormAdminView, self).form_valid(form)
Пример #26
0
 def _set_objects_active(self, request, queryset, active):
     """ Sets the 'is_active' property of each item in ``queryset`` to ``active`` and reports success to the user. """
     # We call save on each object instead of using queryset.update to allow for custom save methods and hooks.
     count = 0
     for obj in queryset.select_for_update():
         obj.is_active = active
         obj.save(update_fields=['is_active'])
         count += 1
     self.message_user(request, _("Successfully %(prefix)sactivated %(count)d %(items)s.") % {
         "prefix": "" if active else "de", "count": count, "items": model_ngettext(self.opts, count)
     })
Пример #27
0
 def sync_selected_items(self, request, queryset):
     n = queryset.count()
     if n:
         for obj in queryset:
             sync_obj(obj, self.model)
         self.message_user(
             request,
             _('Successfully synced %(count)d %(items)s.') % {
                 'count': n,
                 'items': model_ngettext(self.opts, n)
             })
Пример #28
0
def censor_selected(modeladmin, request, queryset):
    """
    Censor the selected submissions, with confirmation interstitial.

    Largely stolen from django.contrib.admin.actions.delete_selected
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        censored_url = request.POST.get('censored_url', None)
        n = queryset.count()
        if n:
            for obj in queryset:
                obj.censor(url=censored_url)
                obj_display = force_unicode(obj)
                modeladmin.message_user(
                    request,
                    _("Censored %(item)s") % {"item": obj_display})
            modeladmin.message_user(
                request,
                _("Successfully censored %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                })
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_unicode(opts.verbose_name)
    else:
        objects_name = force_unicode(opts.verbose_name_plural)

    context = {
        "title": _("Are you sure?"),
        "object_name": objects_name,
        "queryset": queryset,
        "opts": opts,
        "app_label": app_label,
        "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return TemplateResponse(
        request,
        'admin/demos/submission/censor_selected_confirmation.html',
        context,
        current_app=modeladmin.admin_site.name)
Пример #29
0
def make_active(modeladmin, request, queryset):
    n = queryset.count()
    if n:
        for obj in queryset:
            obj_display = force_unicode(obj)
            modeladmin.log_change(request, obj, obj_display)
        queryset.update(is_active=True)
        modeladmin.message_user(request, _("Successfully updated %(count)d %(items)s as active.") % {
            "count": n, "items": model_ngettext(modeladmin.opts, n)
        })
    # Return None to display the change list page again.
    return None
Пример #30
0
def reset_to_pending(modeladmin, request, queryset):
    """ Default action to reset selected object's status to pending """
    ip_count = moderate_selected(modeladmin, request, queryset, PENDING_STATUS)
    if ip_count:
        modeladmin.message_user(
            request,
            _("Successfully reset status of %(count)d %(items)s.") % {
                'count': ip_count,
                'items': model_ngettext(modeladmin.opts, ip_count)
            }
        )
    return None
Пример #31
0
    def form_valid(self, form):
        objects = form.bulk_create(Place)

        if self.model_admin:
            n = len(objects)
            self.model_admin.message_user(
                self.request,
                _("Successfully inserted {count:d} {items}.").format(
                    count=n, items=model_ngettext(self.model_admin.opts, n))
            )

        return super(BulkUploadFormAdminView, self).form_valid(form)
Пример #32
0
def disablereport(modeladmin, request, queryset):
    """
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Populate modifiable_objects, a data structure of all related objects that will also be deleted.
    modifiable_objects, perms_needed = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, levels_to_root=2)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        user = request.user
        # 权限判定
        if not has_manage_perm(user):
            raise PermissionDenied

        n = queryset.count()
        if n:
            for obj in queryset:
                obj_display = force_unicode(obj)
                obj.is_public = False
                obj.save()

                # change
                modeladmin.log_change(request, obj, obj_display)

            modeladmin.message_user(
                request, u'成功 屏蔽 %(count)d %(items)s 报告.' % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                })

        # Return None to display the change list page again.
        return None

    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        "modifiable_objects": modifiable_objects,
        'queryset': queryset,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(
        'disablereport_confirmation.html',
        context,
        context_instance=template.RequestContext(request))
    def really_delete_selected(self, request, queryset):
        # Check that the user has delete permission for the actual model
        if not self.has_delete_permission(request):
            raise PermissionDenied

        for obj in queryset:
            obj.delete()

        n = queryset.count()
        self.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
            "count": n, "items": model_ngettext(self.opts, n)
        })
Пример #34
0
def censor_selected(modeladmin, request, queryset):
    """
    Censor the selected submissions, with confirmation interstitial.

    Largely stolen from django.contrib.admin.actions.delete_selected
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get("post"):
        censored_url = request.POST.get("censored_url", None)
        n = queryset.count()
        if n:
            for obj in queryset:
                obj.censor(url=censored_url)
                obj_display = force_unicode(obj)
                modeladmin.message_user(request, _("Censored %(item)s") % {"item": obj_display})
            modeladmin.message_user(
                request,
                _("Successfully censored %(count)d %(items)s.")
                % {"count": n, "items": model_ngettext(modeladmin.opts, n)},
            )
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_unicode(opts.verbose_name)
    else:
        objects_name = force_unicode(opts.verbose_name_plural)

    context = {
        "title": _("Are you sure?"),
        "object_name": objects_name,
        "queryset": queryset,
        "opts": opts,
        "app_label": app_label,
        "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return TemplateResponse(
        request,
        "admin/demos/submission/censor_selected_confirmation.html",
        context,
        current_app=modeladmin.admin_site.name,
    )
Пример #35
0
def approve_selected(modeladmin, request, queryset):
    """ Default action to approve selected objects """
    ap_count = moderate_selected(modeladmin, request, queryset, APPROVED_STATUS)
    if ap_count:
        modeladmin.message_user(
            request,
            _("Successfully approved %(count)d %(items)s.") % {
                "count": ap_count,
                "items": model_ngettext(modeladmin.opts, ap_count)
            }
        )
    # Return None to display the change list page again.
    return None
Пример #36
0
def challenge_selected(modeladmin, request, queryset):
    """ Default action to challenge selected objects """
    ch_count = moderate_selected(modeladmin, request, queryset, CHALLENGED_STATUS)
    if ch_count:
        modeladmin.message_user(
            request,
            _("Successfully challenged %(count)d %(items)s.") % {
                "count": ch_count,
                "items": model_ngettext(modeladmin.opts, ch_count)
            }
        )
    # Return None to display the change list page again.
    return None
Пример #37
0
def publish_selected(modeladmin, request, queryset):
    opts = modeladmin.model._meta
    app_label = opts.app_label

    all_published = NestedSet()
    for obj in queryset:
        obj.publish(dry_run=True, all_published=all_published)

    perms_needed = []
    _check_permissions(modeladmin, all_published, request, perms_needed)
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied

        n = queryset.count()
        if n:
            for object in all_published:
                modeladmin.log_publication(request, object)

            queryset.publish()

            message = _("Successfully published %(count)d %(items)s.") % {
                "count": n,
                "items": model_ngettext(modeladmin.opts, n)
            }
            modeladmin.message_user(request, message)
            # Return None to display the change list page again.
            return None

    admin_site = modeladmin.admin_site

    context = {
        "title": _("Publish?"),
        "object_name": force_unicode(opts.verbose_name),
        "all_published": _convert_all_published_to_html(admin_site,
                                                        all_published),
        "perms_lacking": _to_html(admin_site, perms_needed),
        'queryset': queryset,
        "opts": opts,
        "root_path": _root_path(admin_site),
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(modeladmin.publish_confirmation_template or [
        "admin/%s/%s/publish_selected_confirmation.html" % (
        app_label, opts.object_name.lower()),
        "admin/%s/publish_selected_confirmation.html" % app_label,
        "admin/publish_selected_confirmation.html"
    ], context, context_instance=template.RequestContext(request))
Пример #38
0
def upload_to_storymarket(modeladmin, request, queryset):
    """
    Admin action to upload selected objects to storymarket.
    """
    opts = modeladmin.model._meta
    post_data = request.POST if request.POST.get('post') else None
    
    # Gather forms, converted data, and other options for later.
    object_info = {}
    for obj in queryset:
        converted_data = converters.convert(obj)
        storymarket_type = converted_data.pop('type')
        form = StorymarketSyncForm(post_data, prefix='sm-%s' % obj.pk, initial=converted_data.copy())
        object_info[obj.pk] = {
            'object': obj,
            'form': form,
            'storymarket_type': storymarket_type,
            'converted_data': converted_data}
    
    if request.POST.get('post') and all(i['form'].is_valid() for i in object_info.values()):
        # The user has confirmed the uploading and has selected valid info.
        num_uploaded = 0
        for obj in queryset:
            info = object_info[obj.pk]
            data = info['converted_data']
            data.update(info['form'].cleaned_data)
            _save_to_storymarket(obj, info['storymarket_type'], data)
            num_uploaded += 1
            
        modeladmin.message_user(request, 
            _("Successfully uploaded %(count)d %(items)s to Storymarket.") % {
                "count": num_uploaded, "items": model_ngettext(modeladmin.opts, num_uploaded)
        })
        return redirect('.')
    
    context = template.RequestContext(request, {
        "app_label": opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "objects": object_info,
    })
    
    template_names = [
        "storymarket/confirm_%s_%s_upload.html" % (opts.app_label, opts.object_name.lower()),
        "storymarket/confirm_upload.html"
    ]
    if hasattr(modeladmin, "storymarket_upload_confirmation_template"):
        template_names.insert(0, modeladmin.storymarket_upload_confirmation_template)
        
    return render_to_response(template_names, context_instance=context)
Пример #39
0
    def send_activation_email(self, request, queryset):
        """
        Send activation emails for the selected users, if they are not already
        activated.
        """
        n = 0
        for user in queryset:
            if not user.is_active and settings.USERS_VERIFY_EMAIL:
                send_activation_email(user=user, request=request)
                n += 1

        self.message_user(
            request, _('Activation emails sent to %(count)d %(items)s.') %
            {'count': n, 'items': model_ngettext(self.opts, n)},  messages.SUCCESS)
Пример #40
0
 def delete_selected_items(self, request, queryset):
     n = queryset.count()
     deleted_items = list(queryset)
     if n:
         for obj in queryset:
             self.log_deletion(request, obj, force_unicode(obj))
         queryset.update(hided=1)
         self._sync_deleted_items(deleted_items)
         self.message_user(
             request,
             _('Successfully deleted %(count)d %(items)s.') % {
                 'count': n,
                 'items': model_ngettext(self.opts, n)
             })
Пример #41
0
    def activate_users(self, request, queryset):
        """
        Activates the selected users, if they are not already
        activated.

        """
        n = 0
        for user in queryset:
            if not user.is_active:
                user.activate()
                n += 1
        self.message_user(
            request,
            _('Successfully activated %(count)d %(items)s.') %
            {'count': n, 'items': model_ngettext(self.opts, n)},  messages.SUCCESS)
Пример #42
0
    def really_delete_selected(self, request, queryset):
        # Check that the user has delete permission for the actual model
        if not self.has_delete_permission(request):
            raise PermissionDenied

        for obj in queryset:
            obj.delete()

        n = queryset.count()
        self.message_user(
            request,
            _("Successfully deleted %(count)d %(items)s.") % {
                "count": n,
                "items": model_ngettext(self.opts, n)
            })
Пример #43
0
def disablereport(modeladmin, request, queryset):
    """
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label
    
    # Populate modifiable_objects, a data structure of all related objects that will also be deleted.
    modifiable_objects, perms_needed = get_deleted_objects(queryset, opts, request.user, modeladmin.admin_site, levels_to_root=2)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.    
    if request.POST.get('post'):
        user = request.user
        # 权限判定
        if not has_manage_perm(user):
            raise PermissionDenied
        
        n = queryset.count()
        if n:
            for obj in queryset :
                obj_display = force_unicode(obj)
                obj.is_public = False
                obj.save()
                
                # change
                modeladmin.log_change(request, obj, obj_display)

            modeladmin.message_user(request, u'成功 屏蔽 %(count)d %(items)s 报告.' % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
        
        # Return None to display the change list page again.
        return None
    
    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        "modifiable_objects": modifiable_objects,
        'queryset': queryset,
        
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response('disablereport_confirmation.html', context, context_instance=template.RequestContext(request))
Пример #44
0
def censor_selected(self, request, queryset):
    """
    Censor the selected submissions, with confirmation interstitial.

    Largely stolen from django.contrib.admin.actions.delete_selected
    """
    opts = self.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not self.has_delete_permission(request):
        raise PermissionDenied

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        censored_url = request.POST.get('censored_url', None)
        n = queryset.count()
        if n:
            for obj in queryset:
                obj.censor(url=censored_url)
                obj_display = force_unicode(obj)
                self.message_user(
                    request,
                    _("Censored %(item)s") % {"item": obj_display})
            self.message_user(
                request,
                _("Successfully censored %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(self.opts, n)
                })
        # Return None to display the change list page again.
        return None

    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        'queryset': queryset,
        "opts": opts,
        "root_path": self.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    tmpl_name = 'admin/demos/submission/censor_selected_confirmation.html'
    return render_to_response(
        tmpl_name, context, context_instance=template.RequestContext(request))
    def delete_akismet_spam(self, request):
        opts = self.model._meta
        app_label = opts.app_label
	perms_needed = False

	# Check that the user has delete permission for the actual model
	if not self.has_delete_permission(request):
		perms_needed = True
	if not self.has_delete_permission(request):
        	raise PermissionDenied


	spam_comments_queryset = MaybeLessSpamComment.objects.all().filter(is_akismet_spam='True')
	n_spam_comments = spam_comments_queryset.count()

	# The user has already confirmed the deletion.
	# Do the deletion and return a None to display the change list view again.
        if request.POST.get('post'):
            if perms_needed:
                raise PermissionDenied
            if n_spam_comments:
                for obj in spam_comments_queryset:
                    obj_display = force_unicode(obj)
                    self.log_deletion(request, obj, obj_display)
		    obj.delete()
                # queryset.delete()
                self.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                    "count": n_spam_comments, "items": model_ngettext(opts, n_spam_comments)
                })
            return HttpResponseRedirect("../")

	title_string = "Delete  %s Akismet-marked spam comments - are you sure?" % n_spam_comments
	deletable_objects = []
	for obj in spam_comments_queryset:
	        deletable_objects.append([mark_safe(u'%s: <a href="../%s/">%s</a>' % (escape(force_unicode(capfirst(opts.verbose_name))), obj.pk, escape(obj))), []])

        # 'current_app':self.admin_site.name
        context = {
            "title": _(title_string),
	    "n_spam_comment": n_spam_comments,
            "perms_lacking": perms_needed,
            "opts": opts,
            "root_path": self.admin_site.root_path,
	    "deletable_objects": deletable_objects,
            "app_label": app_label,
        }
        context_instance = template.RequestContext(request, current_app=self.admin_site.name)
        return render_to_response('admin/%s/delete_akismet_spam.html' % app_label, context, context_instance=context_instance )
Пример #46
0
    def change_course_is_open(self, request, queryset):
        # got from django.contrib.admin.actions
        opts = self.model._meta
        app_label = opts.app_label

        if request.POST.get('post'):
            n = queryset.count()
            if n:
                queryset.update(is_open=True if request.POST['status'] ==
                                'True' else False)
                # TODO: Log the change
                self.message_user(
                    request,
                    _("Successfully changed %(count)d %(items)s.") % {
                        "count": n,
                        "items": model_ngettext(self.opts, n)
                    })
            # Return None to display the change list page again.
            return None

        title = _("Are you sure?")

        if len(queryset) == 1:
            objects_name = force_unicode(opts.verbose_name)
        else:
            objects_name = force_unicode(opts.verbose_name_plural)

        courses = queryset.all()
        editable_objects = []
        for course in courses:
            editable_objects.append(course.__unicode__())

        context = {
            "title": title,
            "objects_name": objects_name,
            "editable_objects": [editable_objects],
            'queryset': queryset,
            "opts": opts,
            "app_label": app_label,
            'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        }

        # Display the confirmation page
        return TemplateResponse(request,
                                'admin/change_course_is_open.html',
                                context,
                                current_app=self.admin_site.name)
Пример #47
0
def export_as_csv_action(modeladmin, request, queryset):
    """
    Exports all selected objects from model
    """
    opts = modeladmin.model._meta
    fields = [field.name for field in opts.fields]
    app_label = opts.app_label
    if request.POST.get('post'):
        fields_wanted = []
        for i in request.POST.items():
            if str(i[0]).startswith('field-'):
                fields_wanted.append(str(i[0])[6:])
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % \
            unicode(opts).replace('.', '_')

        writer = csv.writer(response)
        writer.writerow(list(fields_wanted))

        n = queryset.count()
        if n:
            for obj in queryset:
                writer.writerow([
                    unicode(getattr(obj, field)).encode("utf-8", "replace")
                    for field in fields_wanted
                ])
        _msg_fmt = _("Successfully exported %(count)d %(items)s.")
        _msg = _msg_fmt % {
            "count": n,
            "items": model_ngettext(modeladmin.opts, n)
        }
        modeladmin.message_user(request, _msg)
        return response

    context = {
        "title": _("What do you want export?"),
        "object_name": force_unicode(opts.verbose_name),
        "queryset": queryset,
        "exportable_objects": fields,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }
    req_context = template.RequestContext(request)
    return render_to_response("admin/export_as_csv_action.html",
                              context,
                              context_instance=req_context)
Пример #48
0
    def activate_users(self, request, queryset):
        """
        Activates the selected users, if they are not already
        activated.

        """
        n = 0
        for user in queryset:
            if not user.is_active:
                user.activate()
                n += 1
        self.message_user(
            request,
            _('Successfully activated %(count)d %(items)s.') % {
                'count': n,
                'items': model_ngettext(self.opts, n)
            }, messages.SUCCESS)
Пример #49
0
    def send_activation_email(self, request, queryset):
        """
        Send activation emails for the selected users, if they are not already
        activated.
        """
        n = 0
        for user in queryset:
            if not user.is_active and settings.USERS_VERIFY_EMAIL:
                send_activation_email(user=user, request=request)
                n += 1

        self.message_user(
            request,
            _('Activation emails sent to %(count)d %(items)s.') % {
                'count': n,
                'items': model_ngettext(self.opts, n)
            }, messages.SUCCESS)
Пример #50
0
    def force_unlock(self, request, queryset):
        """
        Admin action to force unlocking all objects in `queryset`.

        Intended for superusers.
        """
        if not self.has_change_permission(request):
            raise PermissionDenied

        for obj in queryset:
            obj.unlock()

        n = queryset.count()

        if n:
            self.message_user(
                request,
                _("Successfully unlocked %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(self.opts, n)
                })
Пример #51
0
def send_newsletter_issue(modeladmin, request, queryset):
    """
    Ask the user to confirm their intent to send a newsletter issue
    before continuing. Based on the delete_selected action from the Django admin.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    if request.POST.get('post'):
        # Do send
        for issue in queryset:
            issue.send()

        # Notify user
        n = queryset.count()
        modeladmin.message_user(
            request,
            _("Successfully sent %(count)d %(newsletters)s.") % {
                'count': n,
                'newsletters': model_ngettext(modeladmin.opts, n)
            })

        # Return None to display the change list page again
        return None

    context = {
        'title': _('Are you sure?'),
        'object_name': force_unicode(opts.verbose_name),
        'queryset': queryset,
        'opts': opts,
        'app_label': app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    return render_to_response(
        'nova/admin/send_selected_confirmation.html',
        context,
        context_instance=template.RequestContext(request))
Пример #52
0
def soft_delete_selected(modeladmin, request, queryset):
    """
    Replace the default delete_selected action so we can soft delete
    objects by using obj.delete() instead of queryset.delete().

    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it soft deletes all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    deletable_objects, perms_needed, protected = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, using)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = queryset.count()
        if n:
            for obj in queryset:
                obj_display = force_unicode(obj)
                modeladmin.log_deletion(request, obj, obj_display)

                # Delete the object with it's own method in case the
                # object has a custom delete method.
                obj.delete()
            modeladmin.message_user(
                request,
                _("Successfully deleted %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                })
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_unicode(opts.verbose_name)
    else:
        objects_name = force_unicode(opts.verbose_name_plural)

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

    context = {
        "title": title,
        "objects_name": objects_name,
        "deletable_objects": [deletable_objects],
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "protected": protected,
        "opts": opts,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return TemplateResponse(request, [
        "admin/%s/%s/soft_delete_selected_confirmation.html" %
        (app_label, opts.object_name.lower()),
        "admin/%s/soft_delete_selected_confirmation.html" % app_label,
        "admin/soft_delete_selected_confirmation.html"
    ],
                            context,
                            current_app=modeladmin.admin_site.name)
Пример #53
0
def _delete_selected(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    # TODO: Permissions would be so cool...
    deletable_objects, perms_needed, protected = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, using)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = len(queryset)
        if n:
            for obj in queryset:
                obj_display = force_text(obj)
                modeladmin.log_deletion(request, obj, obj_display)
                # call the objects delete method to ensure signals are
                # processed.
                obj.delete()
            # This is what you get if you have to monkey patch every object in a changelist
            # No queryset object, I can tell ya. So we get a new one and delete that. 
            #pk_list = [o.pk for o in queryset]
            #klass = queryset[0].__class__
            #qs = klass.objects.filter(pk__in=pk_list)
            #qs.delete()
            modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_text(opts.verbose_name)
    else:
        objects_name = force_text(opts.verbose_name_plural)

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

    context = {
        "title": title,
        "objects_name": objects_name,
        "deletable_objects": [deletable_objects],
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "protected": protected,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }
    
    # Display the confirmation page
    return render_to_response(modeladmin.delete_selected_confirmation_template or [
        "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()),
        "admin/%s/delete_selected_confirmation.html" % app_label,
        "admin/delete_selected_confirmation.html"
    ], context, context_instance=template.RequestContext(request))
Пример #54
0
def delete_selected(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it deletes all selected objects and redirects back to the change
    list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    deletable_objects, perms_needed, protected = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, using)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = queryset.count()
        if n:
            prescription_list = []
            for obj in queryset:
                if obj._meta.object_name == 'Prescription':
                    prescription_list.append(obj.burn_id + ' - ' + obj.name + ' (' + obj.season + ')')
                obj_display = force_text(obj)
                modeladmin.log_deletion(request, obj, obj_display)
            queryset.delete()
            if str(opts) == 'prescription.prescription':
                msg = ''
                for pfp in prescription_list:
                    msg += '<ul>' + pfp + '</ul>'
                modeladmin.message_user(request, _("Successfully deleted the following ePFPs:\n{0}").format(msg),
                                        messages.SUCCESS, extra_tags="safe")
            else:
                modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                    "count": n, "items": model_ngettext(modeladmin.opts, n)
                }, messages.SUCCESS)
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_text(opts.verbose_name)
    else:
        objects_name = force_text(opts.verbose_name_plural)

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

    context = {
        "title": title,
        "objects_name": objects_name,
        "deletable_objects": [deletable_objects],
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "protected": protected,
        "opts": opts,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return TemplateResponse(request, modeladmin.delete_selected_confirmation_template or [
        "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.module_name),
        "admin/%s/delete_selected_confirmation.html" % app_label,
        "admin/delete_selected_confirmation.html"
    ], context, current_app=modeladmin.admin_site.name)
Пример #55
0
def delete_related_objects(modeladmin, request, queryset):
    """
    Action that deletes related objects for the selected items.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it deletes all related objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    first_level_related_objects = []
    first_level_related_objects_by_type = defaultdict(list)
    collector = NestedObjects(using=using)
    collector.collect(queryset)
    for base_object_or_related_list in collector.nested():
        if type(base_object_or_related_list) is not list:
            # If it's not a list, it's a base object. Skip it.
            continue
        for obj in base_object_or_related_list:
            if type(obj) is list:
                # A list here contains related objects for the previous
                # element. We can skip it since delete() on the first
                # level of related objects will cascade.
                continue
            else:
                first_level_related_objects.append(obj)
                first_level_related_objects_by_type[type(obj)].append(obj)

    deletable_objects = []
    model_count = defaultdict(int)
    perms_needed = set()
    protected = []
    # `get_deleted_objects()` fails when passed a heterogeneous list like
    # `first_level_related_objects`, so embark on this rigmarole to spoon-feed
    # it only homogeneous lists
    for homogeneous_list in first_level_related_objects_by_type.values():
        # Populate deletable_objects, a data structure of (string
        # representations of) all related objects that will also be deleted.
        deletable_objects_, model_count_, perms_needed_, protected_ = get_deleted_objects(
            homogeneous_list, opts, request.user, modeladmin.admin_site, using)
        # Combine the results with those from previous homogeneous lists
        deletable_objects.extend(deletable_objects_)
        for k, v in model_count_.iteritems():
            model_count[k] += v
        perms_needed.update(perms_needed_)
        protected.extend(protected_)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = 0
        with transaction.atomic(using):
            for obj in first_level_related_objects:
                obj_display = force_text(obj)
                modeladmin.log_deletion(request, obj, obj_display)
                obj.delete()
                n += 1
        modeladmin.message_user(
            request,
            _("Successfully deleted %(count)d related objects.") % {
                "count": n,
                "items": model_ngettext(modeladmin.opts, n)
            }, messages.SUCCESS)
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_text(opts.verbose_name)
    else:
        objects_name = force_text(opts.verbose_name_plural)

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

    context = dict(
        modeladmin.admin_site.each_context(request),
        title=title,
        objects_name=objects_name,
        deletable_objects=[deletable_objects],
        model_count=dict(model_count).items(),
        queryset=queryset,
        perms_lacking=perms_needed,
        protected=protected,
        opts=opts,
        action_checkbox_name=helpers.ACTION_CHECKBOX_NAME,
    )

    request.current_app = modeladmin.admin_site.name

    # Display the confirmation page
    return TemplateResponse(request,
                            "delete_related_for_selected_confirmation.html",
                            context,
                            current_app=modeladmin.admin_site.name)
Пример #56
0
def delete_selected_popup(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label
    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    deletable_objects, perms_needed, protected = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, using)

    disabled_objects = []

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        query = []
        d = 0
        if perms_needed:
            raise PermissionDenied
        n = queryset.count()

        if n:
            # TODO: create a custom get_delete_objects to put
            # all this validations.
            for obj in queryset:
                obj_display = force_unicode(obj)
                obj_fk = obj._meta.module_name + '_fk'
                obj_name = obj._meta.module_name

                try:
                    if hasattr(Property,
                               obj_fk) and not isinstance(obj, Property):
                        Property.objects.get(**{obj_fk: obj.id})
                        query.append(Q(**{'id': obj.id}))
                        modeladmin.log_change(
                            request, obj, '%s' % _('Logical exclude object.'))
                except ObjectDoesNotExist:
                    modeladmin.log_deletion(request, obj, obj_display)

            # TODO: create a custom get_delete_objects to put
            # all this validations.
            # Exclude objects which has relation with Property to be deleted
            if query:
                # Distinct object to deleted and disabled
                disabled_objects = queryset.filter(reduce(operator.or_, query))
                deletable_objects = queryset.exclude(
                    reduce(operator.or_, query))

                d = disabled_objects.count()
                n = deletable_objects.count()

                # Disable all object was relation with Property
                disabled_objects.update(logical_exclude=True)
            else:
                deletable_objects = queryset

            try:
                # Check if the instance is Realtor models because we have to delete
                # the django User models, when Realtor doesn't has active on Property
                if isinstance(queryset[0], Realtor):
                    for delete_obj in deletable_objects:
                        delete_obj.user.delete()
            except IndexError:
                raise

            deletable_objects.delete()

            if d >= 1 and n >= 1:
                msg = _(
                    "Successfully deleted %(count)d and disabled %(count_two)d %(items_two)s."
                ) % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n),
                    "count_two": d,
                    "items_two": model_ngettext(modeladmin.opts, d)
                }
            elif d >= 1 and n == 0:
                msg = _("Successfully disebled %(count)d %(items)s.") % {
                    "count": d,
                    "items": model_ngettext(modeladmin.opts, d)
                }
            else:
                msg = _("Successfully deleted %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                }

            modeladmin.message_user(request, msg)
        # Return None to display the change list page again.
        return None
    else:

        # Get all object in queryset and check if this object has foreingkey in Property
        # The way to use this delete you have to saw Realto models.
        query = []
        for obj in queryset:
            obj_display = force_unicode(obj)
            obj_fk = obj._meta.module_name + '_fk'
            obj_name = obj._meta.module_name

            # TODO: create a custom get_delete_objects to put
            # all this validations.
            if hasattr(obj, 'user') and isinstance(obj, Realtor):
                protected.append(
                    format_link_callback(obj.user, modeladmin.admin_site))

            if hasattr(Property, obj_fk) and not isinstance(obj, Property):
                try:
                    Property.objects.get(**{obj_fk: obj.id})
                    query.append(Q(**{'id': obj.id}))
                except ObjectDoesNotExist:
                    continue

        # TODO: create a custom get_delete_objects to put
        # all this validations.
        if query:
            disabled_objects = queryset.filter(reduce(operator.or_, query))
            deletable_objects = queryset.exclude(reduce(operator.or_, query))

            if disabled_objects:
                disabled_objects = [
                    format_link_callback(obj, modeladmin.admin_site)
                    for obj in disabled_objects
                ]
            if deletable_objects:
                deletable_objects = [
                    format_link_callback(obj, modeladmin.admin_site)
                    for obj in deletable_objects
                ]

    if (len(deletable_objects) == 1):
        objects_name_delete = force_unicode(opts.verbose_name)
    else:
        objects_name_delete = force_unicode(opts.verbose_name_plural)

    if (disabled_objects and len(disabled_objects) == 1):
        objects_name_disable = force_unicode(opts.verbose_name)
    elif disabled_objects:
        objects_name_disable = force_unicode(opts.verbose_name_plural)
    else:
        objects_name_disable = ''

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

    if deletable_objects:
        try:
            deletable_objects = [
                format_link_callback(obj, modeladmin.admin_site)
                for obj in deletable_objects
            ]
        except:
            pass

    context = {
        "title": title,
        "objects_name_delete": objects_name_delete,
        "objects_name_disable": objects_name_disable,
        "deletable_objects": deletable_objects,
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "protected": protected,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'is_popup': "_popup" in request.REQUEST or "pop" in request.REQUEST,
        'disabled_objects': disabled_objects,
        'queryset_obj_disabled': disabled_objects,
    }

    # Display the confirmation page
    return render_to_response(
        modeladmin.delete_selected_confirmation_template or [
            "admin/%s/%s/delete_selected_confirmation_popup.html" %
            (app_label, opts.object_name.lower()),
            "admin/%s/delete_selected_confirmation_popup.html" % app_label,
            "admin/delete_selected_confirmation_popup.html"
        ],
        context,
        context_instance=template.RequestContext(request))
Пример #57
0
    def delete_selected(self, request, queryset):
        opts = self.model._meta
        app_label = opts.app_label

        # Check that the user has delete permission for the actual model
        if not self.has_delete_permission(request):
            raise PermissionDenied

        using = router.db_for_write(self.model)

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

        # The user has already confirmed the deletion.
        # Do the deletion and return a None to display the change list view again.
        if request.POST.get('post'):
            if perms_needed:
                raise PermissionDenied

            n = queryset.count()
            quarantine =any(result['is_in_quarantine']==True for result in queryset.values('is_in_quarantine'))

            if n:
                for obj in queryset:
                    obj_display = force_text(obj)
                    self.log_deletion(request, obj, obj_display)
                    #remove the object
                    self.delete_model(request, obj)

                self.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                    "count": n, "items": model_ngettext(self.opts, n)
                })
            # Return None to display the change list page again.
            if quarantine:
                url = reverse('admin:notification_taskhistory_changelist')
                return HttpResponseRedirect(url + "?user=%s" % request.user.username)

            return None

        if len(queryset) == 1:
            objects_name = force_text(opts.verbose_name)
        else:
            objects_name = force_text(opts.verbose_name_plural)

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

        context = {
            "title": title,
            "objects_name": objects_name,
            "deletable_objects": [deletable_objects],
            'queryset': queryset,
            "perms_lacking": perms_needed,
            "protected": protected,
            "opts": opts,
            "app_label": app_label,
            'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        }

        # Display the confirmation page

        return TemplateResponse(request, self.delete_selected_confirmation_template or [
            "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()),
            "admin/%s/delete_selected_confirmation.html" % app_label,
            "admin/delete_selected_confirmation.html"
        ], context, current_app=self.admin_site.name)
Пример #58
0
def delete_selected(modeladmin,
                    request,
                    queryset,
                    bypass_django_permissions=False):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied(user=request.user)

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    (deletable_objects, objects_without_delete_perm, perms_needed,
     protected) = get_deleted_contents(queryset, opts, request.user,
                                       modeladmin.admin_site, using,
                                       bypass_django_permissions)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed or objects_without_delete_perm or protected:
            raise PermissionDenied(user=request.user)
        n = queryset.count()
        if n:
            for obj in queryset:
                obj_display = force_unicode(obj)
                modeladmin.log_deletion(request, obj, obj_display)
            queryset.delete()
            modeladmin.message_user(
                request,
                _('Successfully deleted %(count)d %(items)s.') % {
                    'count': n,
                    'items': model_ngettext(modeladmin.opts, n),
                })
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_unicode(opts.verbose_name)
    else:
        objects_name = force_unicode(opts.verbose_name_plural)

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

    context = {
        'title': title,
        'objects_name': objects_name,
        'deletable_objects': [deletable_objects],
        'objects_without_delete_perm': objects_without_delete_perm,
        'queryset': queryset,
        'perms_lacking': perms_needed,
        'protected': protected,
        'opts': opts,
        'root_path': modeladmin.admin_site.root_path,
        'app_label': app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(
        modeladmin.delete_selected_confirmation_template or [
            'admin/%s/%s/delete_selected_confirmation.html' %
            (app_label, opts.object_name.lower()),
            'admin/%s/delete_selected_confirmation.html' % app_label,
            'admin/delete_selected_confirmation.html',
        ],
        context,
        context_instance=template.RequestContext(request))