Home > front end >  Find the type of visible field from visible_fields()
Find the type of visible field from visible_fields()

Time:10-18

I've the following code inside my forms.py. I'm using ModelForm to generate the form view

def __init__(self, *args, **kwargs):
        super(NewPlayerForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            print(visible)
            visible.field.widget.attrs['class'] = 'form-control'

The aim is to not put the form-control class on a field of type boolen/checkbox. But I'm having a hard time in figuring out how to get the field type from the above lines.

print(visible) shows the following in the console

I tried using field.type or field.getType(), nothing seems to work. enter image description here

CodePudding user response:

You can check this by looking for the .field.widget.input_type:

def __init__(self, *args, **kwargs):
    super(NewPlayerForm, self).__init__(*args, **kwargs)
    for visible in self.visible_fields():
        if visible.field.widget.input_type == 'checkbox':
            visible.field.widget.attrs['class'] = 'form-control'
  • Related