我使用管理员对 get_deleted_objects() 的缩减修改,并使用它在删除视图的 get_context 中扩展我的上下文:
在某处定义
from django.contrib.admin.utils import NestedObjects
from django.utils.text import capfirst
from django.utils.encoding import force_text
def get_deleted_objects(objs):
collector = NestedObjects(using='default')
collector.collect(objs)
#
def format_callback(obj):
opts = obj._meta
no_edit_link = '%s: %s' % (capfirst(opts.verbose_name),
force_text(obj))
return no_edit_link
#
to_delete = collector.nested(format_callback)
protected = [format_callback(obj) for obj in collector.protected]
model_count = {model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items()}
#
return to_delete, model_count, protected
那么在你看来
from somewhere import get_deleted_objects
#
class ExampleDelete(DeleteView):
# ...
def get_context_data(self, **kwargs):
#
context = super().get_context_data(**kwargs)
#
deletable_objects, model_count, protected = get_deleted_objects([self.object])
#
context['deletable_objects']=deletable_objects
context['model_count']=dict(model_count).items()
context['protected']=protected
#
return context
现在您可以在模板中使用它们
<table>
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
{% for model_name, object_count in model_count %}
<tr>
<td>{{ model_name|capfirst }}</td>
<td>{{ object_count }}</td>
</tr>
{% endfor %}
</table>
<p>
<ul>
{{ deletable_objects|unordered_list }}
</ul>
</p>
大多数只是从 django admin 复制/粘贴/编辑/删除不需要的内容