Django admin:使字段在添加中可编辑但不可编辑
我有一个与此类似的模型:
class Product(models.Model):
third_party_id = models.CharField(max_length=64, blank=False, unique=True)
它使用 Django 默认主键。我希望用户能够通过在添加页面上设置third_party_id来添加产品,但我不希望该字段在编辑页面中可编辑,以避免损坏third_party_id。在 Django 文档中,相同的设置似乎用于添加和编辑。这可能吗?
I've got a model similar to this:
class Product(models.Model):
third_party_id = models.CharField(max_length=64, blank=False, unique=True)
that uses the Django default primary key. I want users to be able to add products by setting the third_party_id on the add page, but I don't want that field editable in the edit page to avoid corrupting the third_party_id. In the Django docs, the same settings appear to be used for add and edit. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要设置 self.readonly_fields 以避免线程问题。而是重写 get_readonly_fields 方法:
Do not set
self.readonly_fields
to avoid thread issues. Instead override get_readonly_fields method:上面的内容很有帮助(shanyu 使用 get_readonly_fields 的答案),但是如果在“StackedInline”中使用它则无法正常工作。结果是任何标记为只读的字段的两个副本,并且在“add”实例中不可编辑。看到这个错误: https://code.djangoproject.com/ticket/15602
希望这可以拯救某人一些搜索!
The above is helpful (shanyu's answer using get_readonly_fields), however it does not work properly if used in "StackedInline". The result is two copies of whatever field is marked readonly, and it is not editable in the "add" instance. See this bug: https://code.djangoproject.com/ticket/15602
Hope this saves someone some searching!
我不确定这是否是最好的方法,但您可以为管理员定义自己的表单。并自定义验证您的third_party_id,如果已设置则拒绝:
Admin.py
I am not sure if this is the best way, but you could define your own form for the admin. And custom validate your third_party_id, rejecting if it is already set:
Admin.py