Displaying created / modified django_extensions fields in the admin interface
I have a class based on TimeStampedModel
from django-extentions
:
from model_utils.models import TimeStampedModel
class MyClass(TimeStampedModel):
pass
By default, in the admin interface, fields created
and are modified
not displayed on the edit page my_app/myclass/id
.
I tried this hack to force the fields to appear created
and modified
on the admin edit page for MyClass
:
from django.contrib import admin
from my_app.models import MyClass
class MyClassAdmin(admin.ModelAdmin):
fields = MyClass._meta.get_all_field_names()
admin.site.register(MyClass, MyClassAdmin)
But this resulted in the following exception:
Exception Type: FieldError
Exception Value: Unknown field(s) (modified, created) specified for MyClass. Check fields/fieldsets/exclude attributes of class MyClassAdmin.
Any idea how I can display the field created
and modified
in the Admin version MyClass
?
Note 1: MyClass
- This is a model with a lot of fields including fields ManyToMany
. I can display all fields except fields created
and modified
from the base class TimeStampedModel
.
Note 2: The help page in the link is the line edition page:my_app/myclass/id
source to share
The solution is to use the attribute readonly_fields
:
from django.contrib import admin
from my_app.models import MyClass
class MyClassAdmin(admin.ModelAdmin):
readonly_fields = ('created', 'modified', )
admin.site.register(MyClass, MyClassAdmin)
source to share
Created and modified are self-service fields. I think it's not a good idea to "hack" the functionality. You can display these fields in a list as shown below:
For many, many problems:
def <funcname>(self, obj):
return ', '.join([object.<object_field_you_want_to_display> for object in obj.<manyTomanyField>.all()])
<funcname>.short_description = 'Wanted name for column'
Then in list_display:
list_display = (...., '<funcname>')
And then you want to display all the fields you want (created and modified)
list_display(...all fields you want ..., '<funcname>', 'created', 'modified')
But if you still think this is a good idea, you should add these fields to your template (/includes/fieldset.html). But you have to write a context processor and / or template tag first to get the value of the entry ... and so on ...
source to share