Django Admin - Overriding the widget of a custom form field

I have my own 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 you can see above, it uses the TextInput form field widget. But in admin, I would like it to be displayed using the Textarea widget. There is a formfield_overrides hook for formfield_overrides , but it does not work for this case.

Ad Ad:

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

This does not affect the form field widget, and tags is still displayed using the TextInput widget.

Any help is greatly appreciated.

- OMAT Page

+27
override django django-admin widget
Aug 12 '10 at 16:43
source share
4 answers

The django admin uses custom widgets for many of his fields. A way to override fields is to create a form for use with the ModelAdmin object.

 # forms.py from django import forms from django.contrib import admin class ProductAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductAdminForm, self).__init__(*args, **kwargs) self.fields['tags'].widget = admin.widgets.AdminTextareaWidget() 

Then in your ModelAdmin object you specify the form:

 from django.contrib import admin from models import Product from forms import ProductAdminForm class ProductAdmin(admin.ModelAdmin): form = ProductAdminForm admin.site.register(Product, ProductAdmin) 

You can also redefine the set of queries at the moment: to filter objects by another field in the model, for example (since limit_choices_to cannot handle this)

+44
Dec 17 '10 at 1:30
source share

You can override field widgets by extending the ModelForm Meta class with Django 1.2:

 class ProductAdminForm(forms.ModelForm): class Meta: model = Product widgets = { 'tags': admin.widgets.AdminTextareaWidget } class ProductAdmin(admin.ModelAdmin): form = ProductAdminForm 

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-fields

+34
Apr 24 2018-12-12T00:
source share

Try changing the field as follows:

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

This will allow you to use the widget that comes from **kwargs . Otherwise, your field will always use the form.TextInput widget.

+2
Aug 12 '10 at 17:02
source share

For a specific field, not the field that I use:

Django 2.1.7

 class ProjectAdminForm(forms.ModelForm): class Meta: model = Project fields = '__all__' widgets = { 'project_description': forms.Textarea(attrs={'cols': 98}) } 
 class ProjectAdmin(admin.ModelAdmin): form = ProjectAdminForm 

Thank @Murat Γ‡orlu

0
Apr 12 '19 at 10:34
source share



All Articles