在Django中,我们为ModelAdmin提供了save_as
参数,在某些对象的管理员网站编辑页面上启用了“另存为新”按钮。
但是当默认情况下对象(Model1实例)与其他模型(Model2)有关系时,我想以下列方式编辑Model2实例:默认为当前关系(取决于Model2实例字段)Model1实例和编辑它的一些字段,我点击编辑按钮,弹出窗口,我可以在那里更改一些字段,但不能将该对象保存为新的,所以我有2个选项:破坏默认对象或复制粘贴每个字段相关对象进入“添加新”弹出窗口。
我想在“编辑”弹出窗口中添加“另存为新”按钮。
我发现,使用name="_saveasnew"
和value=1
添加隐藏输入实际上会保存另一个模型,但是如何使用特殊按钮添加它?
另外,弹出窗口的按钮上有一个特殊的块,我看到:https://github.com/django/django/blob/1.8/django/contrib/admin/templatetags/admin_modify.py#L39(是的,我们使用Django 1.8 :() 什么是最佳解决方案:编辑模板或编辑标签本身?
答案 0 :(得分:0)
正确的解决方案是使用您自己的submit_row
模板标记进行弹出窗口,为此,您必须覆盖admin/change_form.html
模板的块:submit_buttons_top
和submit_buttons_bottom
:
{% extends "admin/change_form.html" %}
{% load YOUR_TEMPLATE_TAGS %}
{% block submit_buttons_top %}{% YOUR_SUBMIT_ROW_TAG %}{% endblock %}
{% block submit_buttons_bottom %}{% YOUR_SUBMIT_ROW_TAG %}{% endblock %}
新submit_row
代码的代码的主要区别在于更改了上下文密钥:'show_save_as_new': change and save_as,
YOUR_TEMPLATE_TAGS.py
的代码看起来像这样:
from django import template
register = template.Library()
@register.inclusion_tag('admin/submit_line.html', takes_context=True)
def YOUR_SUBMIT_ROW_TAG(context):
"""
Displays the row of buttons for delete and save.
HINT: override of default django `submit_row` tag, changes:
`save as new` button is displayed for popup.
"""
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
new_context = {
'opts': opts,
'show_delete_link': (
not is_popup and context['has_delete_permission'] and
change and context.get('show_delete', True)
),
'show_save_as_new': change and save_as,
'show_save_and_add_another': (
context['has_add_permission'] and not is_popup and
(not save_as or context['add'])
),
'show_save_and_continue': not is_popup and context['has_change_permission'],
'is_popup': is_popup,
'show_save': True,
'preserved_filters': context.get('preserved_filters'),
}
if context.get('original') is not None:
new_context['original'] = context['original']
return new_context