Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show object ID (primary key) in Django admin object page

Assuming I have the following 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.site.register(Book)

When viewing an existing Book in admin, only the name field is visible.

My question is: Can the ID also be visible in this page?

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. However, I would like to keep it read-only.

like image 370
Demetris Avatar asked Nov 06 '17 14:11

Demetris


2 Answers

You can add it to readonly_fields in the modeladmin class.

class BookAdmin(admin.ModelAdmin):
    readonly_fields = ('id',)

admin.site.register(Book, BookAdmin)
like image 191
Daniel Roseman Avatar answered Sep 18 '22 11:09

Daniel Roseman


EDIT

I removed my answer since it was the same as @DanielRoseman, but this is just for clarification. This is from the documentation:

If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.

Therefore, using readonly_fields is the way to go.

like image 20
scharette Avatar answered Sep 19 '22 11:09

scharette