简体   繁体   English

Django:如何更改内联Formset中的字段小部件

[英]Django: How to change a field widget in a Inline Formset

I am new to Django and I think I am missing this in the docs. 我是Django的新手,我想我在文档中遗漏了这个。
The problem is that in inline-formset I dont declare a form, just pass two models to construct it. 问题是在inline-formset中我没有声明一个表单,只需传递两个模型来构造它。
I want to know how can I change a widget of a single field using inline formset? 我想知道如何使用内联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: 从Django 1.6开始 ,您可以使用modelformset_factorywidgets参数来自定义特定字段的窗口小部件:

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

and therefore the same parameter for inlineformset_factory (which uses modelformset_factory ): 并且因此对于相同的参数inlineformset_factory (使用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: 这是使用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. 您需要在Meta类中定义表单和更新小部件。 Look at Overriding the default field types or widgets 查看覆盖默认字段类型或小部件

you can subclass the formset and override the add_fields method. 您可以子类化formset并覆盖add_fields方法。 This worked for me and I am using Django 1.5 :( . 这对我有用,我正在使用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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM