Django:只读字段
如何允许用户在创建对象(“添加”页面)时填充字段,然后在“更改”页面访问时将其设置为只读?
How do I allow fields to be populated by the user at the time of object creation ("add" page) and then made read-only when accessed at "change" page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我发现的最简单的解决方案是覆盖 ModelAdmin 的 get_readonly_fields 函数:
对于添加页面,对象将是 none,对于更改页面,对象将是模型的实例。
编辑:请注意这是在 Django==1.2 上测试的
The simplest solution I found was to override the get_readonly_fields function of ModelAdmin:
Object will be none for the add page, and an instance of your model for the change page.
Edit: Please note this was tested on Django==1.2
你的问题中有两件事需要解决。
1.只读表单字段
在Django中不存在,但你可以自己实现,并且这篇博文可以提供帮助。
2.添加/更改的不同形式
我猜您正在管理站点上下文中寻找解决方案(否则,只需在视图中使用两种不同的形式)。
您最终可以在
ModelAdmin
中覆盖add_view
或change_view
并在其中一个视图中使用不同的表单,但恐怕您会结束充满了可怕的重复代码。我能想到的另一个解决方案是,当传递
instance
参数(即:edit 情况)时,该表单将在实例化时修改其字段。假设您有一个 ReadOnlyField 类,它会给您类似的内容:在这里,模型
Stuff
中的字段title
将是只读的在管理站点的更改页面上,但可以在创建表单上进行编辑。希望有帮助。
There's two thing to address in your question.
1. Read-only form fields
Doesn't exist as is in Django, but you can implement it yourself, and this blog post can help.
2. Different form for add/change
I guess you're looking for a solution in the admin site context (otherwise, just use 2 different forms in your views).
You could eventually override
add_view
orchange_view
in yourModelAdmin
and use a different form in one of the view, but I'm afraid you will end up with an awful load of duplicated code.Another solution I can think of, is a form that will modify its fields upon instantiation, when passed an
instance
parameter (ie: an edit case). Assuming you have aReadOnlyField
class, that would give you something like:In here, the field
title
in the modelStuff
will be read-only on the change page of the admin site, but editable on the creation form.Hope that helps.
您可以编辑该模型的保存方法来处理此类要求。例如,您可以检查该字段是否已包含某个值,如果包含,则忽略新值。
You can edit that model's save method to handle such a requirement. For example, you can check if the field already contains some value, if it does, ignore the new value.
一种选择是覆盖或替换该特定模型的change_form模板。
One option is to override or replace the change_form template for that specific model.