user14411637
user14411637

Reputation:

Show created and edited fields in Django admin form

I have this model

class Volunteer(models.Model):
STATUSES = (
    ('Active', 'Active'),
    ('Paused', 'Paused'),
    ('Inactive', 'Inactive'),
)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email_address = models.CharField(max_length=100, null=True, blank=True)
picture = models.ImageField(null=True, blank=True)
status = models.CharField(max_length=20, choices=STATUSES, default="Active")
created = models.DateTimeField(auto_now_add=True, editable=False)
edited = models.DateTimeField(auto_now=True, editable=False)

And I register it like this

class VolunteerAdmin(admin.ModelAdmin):
fields = ('first_name', 'last_name', 'email_address', 'status', 'created', 'edited')
list_display = ('first_name', 'last_name', 'email_address', 'status')
list_editable = ('status',)
list_filter = ('status',)
search_fields = ('first_name', 'last_name')

admin.site.register(Volunteer, VolunteerAdmin)

I get an error because I have manually added the created and edited fields as I want to see them in the view/edit forms. I know that the user should not be able to change these so I set the attributes to editable=False for both. However, it throws an error. Any idea what I need to do to be able to display these two fields in my admin forms?

This is my error: 'created' cannot be specified for Volunteer model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class VolunteerAdmin.

Thanks for your help.

Upvotes: 1

Views: 1861

Answers (2)

TheSohan
TheSohan

Reputation: 440

You should consider adding created and edited in read-only fields like:

readonly_fields = ('created','edited')

Complete code snippet:

class VolunteerAdmin(admin.ModelAdmin):
    fields = ('first_name', 'last_name', 'email_address', 'status','created','edited')
    list_display = ('first_name', 'last_name', 'email_address', 'status')
    list_editable = ('status',)
    readonly_fields = ('created','edited')
    list_filter = ('status',)
    search_fields = ('first_name', 'last_name')

admin.site.register(Volunteer, VolunteerAdmin)

Upvotes: 2

taha maatof
taha maatof

Reputation: 2165

i think you could just get rid of the fields line ,add 'created', 'edited' to list of display if you want, usually you can see the field automatically in the detail of every volunteer,

maybe because you did it manually it got stuck, in that case delete your last migration and database (sqlite) and re-do makemagrations and migrate.

also if you are usning a form in a forms.py to be used in a template you should exclude 'created',and 'edited', because you cant edit them.

Upvotes: 0

Related Questions