[英]Show object ID (primary key) in Django admin object page
Assuming I have the following model.py
: 假设我有以下
model.py
:
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100, unique=True)
I register this model in the admin.py
using: 我使用以下命令在
admin.py
注册此模型:
admin.site.register(Book)
When viewing an existing Book
in admin, only the name
field is visible. 在管理员中查看现有
Book
时,只显示name
字段。
My question is: Can the ID also be visible in this page? 我的问题是:此页面中是否也可以看到ID?
Most of the answers I find are related to the admin list rather than the object instance page. 我发现的大多数答案都与管理列表而不是对象实例页面有关。 One way to show the ID field is to make it editable by removing
editable=False
from the model definition. 显示ID字段的一种方法是通过从模型定义中删除
editable=False
使其可editable=False
。 However, I would like to keep it read-only. 但是,我想将它保持为只读。
You can add it to readonly_fields
in the modeladmin class. 您可以将它添加到modeladmin类中的
readonly_fields
。
class BookAdmin(admin.ModelAdmin):
readonly_fields = ('id',)
admin.site.register(Book, BookAdmin)
EDIT 编辑
I removed my answer since it was the same as @DanielRoseman, but this is just for clarification. 我删除了我的答案,因为它和@DanielRoseman一样,但这只是为了澄清。 This is from the documentation :
这来自文档 :
If False, the field will not be displayed in the admin or any other ModelForm.
如果为False,则该字段不会显示在admin或任何其他ModelForm中。 They are also skipped during model validation.
在模型验证期间也会跳过它们。 Default is True.
默认为True。
Therefore, using readonly_fields is the way to go. 因此,使用readonly_fields是可行的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.