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
The way to override fields is to create a Form for use with the ModelAdmin object. This didn't work for me, you need to pass an instance of the widget, rather than the class. The instance worked perfectly, though. I typically would create custom admin forms in the admin.py and not mix them in with forms.py.
Overriding the default fields To specify a custom widget for a field, use the widgets attribute of the inner Meta class. This should be a dictionary mapping field names to widget classes or instances. The widgets dictionary accepts either widget instances (e.g., Textarea(...) ) or classes (e.g., Textarea ).
You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.
A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <!
The django admin uses custom widgets for many of its fields. The 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 override the queryset at this time: to filter objects according to another field in the model, for instance (since limit_choices_to
cannot handle this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With