Home > Enterprise >  Add attribute to the checkbox field based on initial django form
Add attribute to the checkbox field based on initial django form

Time:09-23

class MyForm(Form):
    real = BooleanField()

If MyForm(data={'real': 'on'}), I want to render <input type="checkbox" checked=checked data-initial='on'>.

If MyForm(data={}), I want to render <input type="checkbox">.

How to achieve this?

CodePudding user response:

You need to overwrite init of MyForm class:

from django import forms

class MyForm(forms.Form):
    real = forms.BooleanField()

    def __init__(self, *args, **kwargs):
        data = kwargs.pop('data')
        super(MyForm, self).__init__(*args, **kwargs)
        if data != {} and 'real' in data:
            self.fields['real'] = forms.BooleanField(initial=True, widget=forms.CheckboxInput(attrs={'data-initial': data['real']}))

so if real is passed as key in data dict it will make real field initialy True (checked) and value will be pass to data-initial attr.

  • Related