【问题标题】:How to add all remaining model fields to a django crispy form layout?如何将所有剩余的模型字段添加到 django 脆表单布局?
【发布时间】:2019-12-18 00:52:03
【问题描述】:

我正在使用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
        )

如果我呈现此表单,它将只有一个字段。如何使用默认布局值/设置添加其余部分?

【问题讨论】:

    标签: django-crispy-forms


    【解决方案1】:

    我认为最好的方法是使用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],
            )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-11
      • 2019-10-20
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2023-03-11
      相关资源
      最近更新 更多