views:

147

answers:

1

Hi All,

I have a custom TagField form field.

class TagField(forms.CharField):
    def __init__(self, *args, **kwargs):
        super(TagField, self).__init__(*args, **kwargs)
        self.widget = forms.TextInput(attrs={'class':'tag_field'})

As seen above, it uses a TextInput form field widget. But in admin I would like it to be displayed using Textarea widget. For this, there is formfield_overrides hook but it does not work for this case.

The admin declaration is:

class ProductAdmin(admin.ModelAdmin):
    ...
    formfield_overrides = {
        TagField: {'widget': admin.widgets.AdminTextareaWidget},
    }

This has no effect on the form field widget and tags are still rendered with a TextInput widget.

Any help is much appreciated.

--
omat

A: 

Try to change your field like this:

class TagField(forms.CharField):
    def __init__(self, *args, **kwargs):
        self.widget = forms.TextInput(attrs={'class':'tag_field'})
        super(TagField, self).__init__(*args, **kwargs)

This would allow to use the widget which comes from **kwargs. Otherwise your field will always use form.TextInput widget.

Andrey Fedoseev
i applied the change but now all tag fields are rendered as Textarea.
omat
Looking at django.forms.fields I found that the correct way to specify the default widget for a field is: class TagField(form.CharField): widget = forms.TextInput def widget_attrs(self, widget): return {'class': 'tag_field'}You don't have override the `__init__` method. Try this.
Andrey Fedoseev
thanks but still no luck. all tag fields are displayed as Textarea, all over the admin, not just for ProductAdmin.
omat