Django: How to change a field widget in a Inline Formset Django: How to change a field widget in a Inline Formset django django

Django: How to change a field widget in a Inline Formset


As of Django 1.6, you can use the widgets parameter of modelformset_factory in order to customize the widget of a particular field:

AuthorFormSet = modelformset_factory(Author, widgets={    'name': Textarea(attrs={'cols': 80, 'rows': 20})})

and therefore the same parameter for inlineformset_factory (which uses modelformset_factory):

AuthorInlineFormSet = inlineformset_factory(Author, Book, fields=['name'], widgets={    'name': Textarea(attrs={'cols': 80, 'rows': 20})})


This is an example of customizing one field using formfield_callback:

def formfield_callback(field):    if isinstance(field, models.ChoiceField) and field.name == 'target_field_name':        return fields.ChoiceField(choices = SAMPLE_CHOICES_LIST, label='Sample Label')    return field.formfield()FormSet = inlineformset_factory(ModelA, ModelB, extra=1, formfield_callback = formfield_callback)


You need to define a form and update widget in the Meta class. Look at Overriding the default field types or widgets