Django admin - 如果编辑对象则删除字段
我有一个可以通过 Django 管理区域访问的模型,如下所示:
# model
class Foo(models.Model):
field_a = models.CharField(max_length=100)
field_b = models.CharField(max_length=100)
# admin.py
class FooAdmin(admin.ModelAdmin):
pass
假设我想在用户添加对象时显示 field_a 和 field_b,但如果用户正在编辑对象则仅显示 field_a。有没有一种简单的方法可以做到这一点,也许使用 fields 属性?
如果到了这个地步,我可以破解一个 JavaScript 解决方案,但这样做感觉根本不对!
I have a model which is accessible through the Django admin area, something like the following:
# model
class Foo(models.Model):
field_a = models.CharField(max_length=100)
field_b = models.CharField(max_length=100)
# admin.py
class FooAdmin(admin.ModelAdmin):
pass
Let's say that I want to show field_a and field_b if the user is adding an object, but only field_a if the user is editing an object. Is there a simple way to do this, perhaps using the fields attribute?
If if comes to it, I could hack a JavaScript solution, but it doesn't feel right to do that at all!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为管理员创建一个自定义
ModelForm
,以将该字段放入__init__
编辑:从 John 的评论中获取有关使字段只读的提示,您可以将其设置为隐藏字段并覆盖 clean 以确保值不会更改。
You can create a custom
ModelForm
for the admin to drop the field in the__init__
EDIT: Taking a hint from John's comment about making the field read-only, you could make this a hidden field and override the clean to ensure the value doesn't change.
您还可以执行以下
操作Django admin:排除更改字段仅表格
You can also do the following
Taken from here Django admin: exclude field on change form only