Custom admin widgets by field type

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django import forms
from django.forms import fields, widgets

class BaseAdminTextInputWidget(widgets.TextInput):
    def __init__(self, *args, **kwargs):
        super(BaseAdminTextInputWidget, self).__init__(*args, **kwargs)
        self.attrs.update({
            'size': '75',
        })

WIDGET_OVERRIDES = [
    (fields.CharField, BaseAdminTextInputWidget),
]

def override_widget(fields, field_type, widget):
    for name,field in fields.items():
        if isinstance(field, field_type):
            field.widget = widget()

class BaseAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BaseAdminForm, self).__init__(*args, **kwargs)
        for field_type, widget in WIDGET_OVERRIDES:
            override_widget(self.fields, field_type, widget)

def get_admin_form(form_model):
    class ModelAdminForm(BaseAdminForm):
        class Meta:
            model = form_model
    return ModelAdminForm

More like this

  1. DisplayModelForm by koenb 5 years ago
  2. Play nice with ModelAdmin mixins by chris.dickinson 4 years, 4 months ago
  3. ImageField for admin with thumbnail by semente 3 years, 11 months ago
  4. GeoDjango maps in admin TabularInlines by alanB 2 years, 7 months ago
  5. Django Admin Replacer Code by riccardodivirgilio 2 years, 6 months ago

Comments

david_bgk (on March 11, 2009):

Why don't you use formfield_overrides option?

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#formfield-overrides

#

(Forgotten your password?)