Search code examples
djangodjango-crispy-forms

django-crispy-forms split form in two divs layout


I want to split a form into two divs with their own css_id so I can ajax update second div based on choices in the first. Problem is that my resulting form does not have divs with ids 'pbid' and 'pb-options'

class PBForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)

        self.layout = Layout(
            Div('cc', 'pb_id', css_id="pbid"),
            Div('closed_r', 'closed_l', css_id="pb-options")
        )

    pb_id = forms.ChoiceField(label='PB', widget=forms.RadioSelect)
    closed_l = forms.ChoiceField(label='Left Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES)
    closed_r = forms.ChoiceField(label='Right Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES)

    class Meta:
        model = pb 
        fields = ['cc', 'pb_id', 'closed_r', 'closed_l']

Solution

  • You assign it to the .layout of the FormHelper:

    class PBForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.helper = FormHelper(self)
            #   🖟 .helper
            self.helper.layout = Layout(
                Div('cc', 'pb_id', css_id='pbid'),
                Div('closed_r', 'closed_l', css_id='pb-options'),
            )