Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add all remaining model fields to a django crispy form layout?

I'm using django-crispy-forms, and I have a form with many fields. I only want to customize a few of those fields, for example:

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
        )

If I render this form, it will only have the one field. How do I add the rest of them with their default layout values/settings?

like image 597
43Tesseracts Avatar asked Sep 18 '25 05:09

43Tesseracts


1 Answers

I think the best way to do this would be to use the get_fields method of Django's Option class, which is available on your model's ._meta property, combined with star-unpacking. Like so:

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],
        )
like image 55
YellowShark Avatar answered Sep 23 '25 07:09

YellowShark