Add onclick event radio buttons django forms

So i have a form i use django forms to render out and i have radio buttons that i have added the onclick function to using the code below.

class Profile(forms.ModelForm):
    class Meta:
        model = User
        fields = [
            "username",
            "email",
            "first_name",
            "last_name",
            "avatar",
            "staff_id",
            "matric_no",
            "library_id",
            "designation",
            "lib_user",
        ]
        widgets = {
            "designation": forms.RadioSelect(attrs={
                "id":"label_68",
                "class":"form-radio validate[required]",
                "required":"", 
                "name":"q68_typeA68",
                "onclick":"myFunction(0)",
            }),
        }

whenever the form is rendered in html, it look like this

<input type="radio" name="lib_user" value="" id="label_70_0" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)">
<input type="radio" name="lib_user" value="Yes" id="label_70_1" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)">
<input type="radio" name="lib_user" value="No" id="label_70_2" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)">

what i want to achieve is this

<input type="radio" name="lib_user" value="" id="label_70_0" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)">
<input type="radio" name="lib_user" value="Yes" id="label_70_1" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(1)">
<input type="radio" name="lib_user" value="No" id="label_70_2" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(2)">

So how do i go about it is what i need help with.

Try doing this, what it does is overwrite the init method of the Profile form and the for loop goes through the widgets and adds the onclick event:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    for i, (value, widget) in enumerate(self.fields["lib_user"].widget.choices):
        widget.attrs["onclick"] = f"myFunction1({i})"
Back to Top