这是一个答案,只用几行代码和几个模板更改就可以满足我的要求:
class MyModelAdmin(admin.ModelAdmin):
fieldsets = [...]
def get_readonly_fields(self, request, obj=None):
if 'edit' not in request.GET:
return <list all fields here>
else:
return self.readonly_fields
现在 change_form 的常用 URL 将生成只读的 change_form,但如果您在 URL 后附加“?edit=1”,您将能够进行编辑。
还可以根据 URL 中是否包含“?edit=1”来自定义 change_form 模板。为此,请将'django.core.context_processors.request' 放入TEMPLATE_CONTEXT_PROCESSORS 放入settings.py,然后在模板中使用request.GET.edit。
例如,要在不处于编辑模式时添加“编辑”按钮,请插入
{% if not request.GET.edit %}
<li><a href="?edit=1">Edit</a></li>
{% endif %}
就在<ul class="object-tools"> 之后的change_form.html。
作为另一个例子,将change_form.html 更改为包含
{% if save_on_top and request.GET.edit %}{% submit_row %}{% endif %}
将意味着提交行将仅在编辑模式下显示。也可以使用这种方法隐藏内联等上的删除按钮。
作为参考,这是我在settings.py中输入的内容:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.contrib.messages.context_processors.messages',
# Above here are the defaults.
'django.core.context_processors.request',
)