AmirW
AmirW

Reputation: 816

Showing DateTimeField with editable=False in django admin

I have date field which is editable=False.

The field is populated with datetime.now() at creation time.

Since admin will not show editable=False fields, I created a custom admin.

The custom admin uses a form with this field:

date = forms.DateTimeField(widget=widgets.AdminSplitDateTime, required=False)

What I want to achieve is this:

  1. users will not be able to touch this field (hence, editable=False)
  2. Admin will be able to change the field's value but won't be forced to (this is why I have required=False)
  3. Admin will be able to see the current value of the field.

I'm failing to achieve (3). I create an entry, and I see that it has a valid date when I look in the database. But when I open it from admin panel, the date widget is empty.

Any ideas how to make the date widget show the current value of the field?

Upvotes: 0

Views: 1605

Answers (1)

okm
okm

Reputation: 23871

First, models.DateTimeField uses widgets.AdminSplitDateTime by default in the Admin, you don't have to specify it explicitly.

For normal staff, use readonly_fields to prevent the date field from being changed.

For administrator, render a different changing form to allow the modification towards the date field. In Django 1.4, it can be easily done by overriding ModelAdmin.get_readonly_fields():

class YourModelAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        # we don't use self.readonly_fields anymore
        if request.user.is_superuser:
            return ()
        return ['date']

Upvotes: 2

Related Questions