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

后端 未结 4 1714
深忆病人
深忆病人 2021-02-13 07:21

I am new to Django and I think I am missing this in the docs.
The problem is that in inline-formset I dont declare a form, just pass two models to construct it.
I want

相关标签:
4条回答
  • 2021-02-13 07:40

    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)
    
    0 讨论(0)
  • 2021-02-13 07:42

    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())
    
    0 讨论(0)
  • 2021-02-13 07:43

    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})
    })
    
    0 讨论(0)
  • 2021-02-13 08:07

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

    0 讨论(0)
提交回复
热议问题