Belmin Fernandez Belmin Fernandez - 1 year ago 135
Python Question

Django Admin: Using a custom widget for only one model field

I have a DateTimeField field in my model. I wanted to display it as a checkbox widget in the Django admin site. To do this, I created a custom form widget. However, I do not know how to use my custom widget for only this one field.

The Django documentation explains how to use a custom widget for all fields of a certain type:

class StopAdmin(admin.ModelAdmin):
formfield_overrides = {
models.DateTimeField: {'widget': ApproveStopWidget }

This is not granular enough though. I want to change it for only one field.

Answer Source

Create a custom ModelForm for your ModelAdmin and add 'widgets' to its Meta class, like so:

class StopAdminForm(forms.ModelForm):
  class Meta:
    model = Stop
    widgets = {
      'approve_ts': ApproveStopWidget(),
    fields = '__all__'

class StopAdmin(admin.ModelAdmin):
  form = StopAdminForm


Documentation for this is sort of non-intuitively placed in the ModelForm docs, without any mention to it given in the admin docs. See: Creating forms from models

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download