如何将所有剩余的模型字段添加到django脆皮表单布局中?

时间:2019-08-10 17:33:06

标签: django-crispy-forms

我正在使用django-crispy-forms,并且我有一个包含许多字段的表单。我只想自定义其中一些字段,例如:

class ExampleForm(forms.ModelForm):
    model = ExampleModel
    fields = "__all__" # tons of fields

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('readonlyfield', readonly=True),
            # Add rest of fields here without explicitly typing them all out
        )

如果我渲染此表单,它将只有一个字段。如何添加其余的默认布局值/设置?

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是将get_fields method of Django's Option class(与模型的._meta属性一起使用)与star-unpacking结合使用。像这样:

class ExampleForm(forms.ModelForm):
    model = ExampleModel
    fields = "__all__" # tons of fields

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()

        # This list contains any fields that you are explicitly typing out / adding to the Layout
        manually_rendered_fields = ['readonlyfield',]

        # Next, create an array of all of the field name BESIDES the manually_rendered_fields
        all_other_fields = [f.name for f in self.model._meta.get_fields() if f not in manually_rendered_fields]

        self.helper.layout = Layout(
            Field('readonlyfield', readonly=True),
            # Add rest of fields here without explicitly typing them all out
            *all_other_fields,
            # if you needed to provide custom kwargs for the other fields, you could do something like this instead:
            *[Field(f, kwarg1=True, kwarg2=False) for f in all_other_fields],
        )