Customize forms.CheckboxInput HTML rendering

I’m using forms.ModelForm to define form.
As one of the widgets I have forms.CheckboxInput.

The problem I have is that forms.CheckboxInput is rendering <label> before <input>.

How can I achieve that <input> is rendered before <label> ?

I have many other fields in the model, so going to rewrite the whole thing manually is really not an option for me because I like what I get with forms.ModelForm - I have only a problem with forms.CheckboxInput.
So please suggest how to solve this quickly…

# forms.py
class SubscriberCreateForm(forms.ModelForm):
    class Meta:
        model = Subscriber
        fields = # many fields
        widgets = {
			# many other fields
			'has_consented':forms.CheckboxInput(attrs={'id': 'checkbox'}),
        }
        labels = {
            # many other fields
			'email':'I confirm...',
        }

This is rendered HTML:

<!-- Rendered HTML -->
<p>
    <label for="checkbox">I confirm...</label>
    <input type="checkbox" name="has_consented" id="checkbox">
</p>

And this is what I need:

<p>
    <input type="checkbox" name="has_consented" id="checkbox">
    <label for="checkbox">I confirm...</label>
</p>

Thank you !!

I would suggest creating a custom template (based on the existing checkbox template), and create a custom widget that would use your template. You can then define that checkbox to use your custom widget.

1 Like

Thanks.

I inherited original CheckboxInput class and just point to my customly created checkbox template:

class CustomCheckboxInput(forms.CheckboxInput):
    template_name = 'myapp/forms_widgets/checkbox_custom.html'
1 Like