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

天涯浪子 提交于 2019-12-04 01:00:01

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

you can subclass the formset and override the add_fields method. This worked for me and I am using Django 1.5 :( .

AuthorInlineFormSet = inlineformset_factory(Author, Book)
class AuthorFormSet(AuthorInlineFormSet):
        def add_fields(self, form, index):
            super(ReferenceForm,self).add_fields(form,index)
            form.fields["name"] = forms.CharField(widget=forms.TextInput())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!