I'm trying to display two new rows (fields) in the "posts" section of django admin which are read-only fields that take data from two other database columns. My code works, but it will not create two new fields, it only displays one.
I'm relatively new to Django and python, and I'm struggling to figure out how to do this. I spent too much time trying different things only to have no success.
In the context of my test, I want to see two readonly fields called "New row 1" and "New row 2", which take the data from two database columns called "est_completion_time" and "downtime". I can only see "New row 2" on the output.
This is my code in admin.py:
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
form = JBForm
exclude = ['est_completion_time'] # hide this database column
exclude = ['downtime'] # hide this database column
readonly_fields = ['placeholder_1'] # display this one
readonly_fields = ['placeholder_2'] # display this one
@admin.display(description="New row 1")
def placeholder_1(self, obj):
return obj.est_completion_time # a new readonly field which should display contents of 'est_completion_time' column
@admin.display(description='New row 2')
def placeholder_2(self, obj):
return obj.downtime # a new readonly field which should display contents of 'downtime' column
After reading through the docs I couldn't find a solution:
https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets
https://docs.djangoproject.com/en/4.0/ref/contrib/admin/actions/
Any help would be greatly appreciated.
CodePudding user response:
I believe you need to specify the excluded
and readonly_fields
once.
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
form = JBForm
exclude = ["est_completion_time", "downtime"]
readonly_fields = ["placeholder_1", "placeholder_2"] # display these two
@admin.display(description="New row 1")
def placeholder_1(self, obj):
return obj.est_completion_time
@admin.display(description="New row 2")
def placeholder_2(self, obj):
return obj.downtime