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?
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],
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With