1

I want to change widget for all BooleanField's in model to Yes/No radio buttons, thought it will be simple:

 def __init__(self, *args, **kwargs):
    logger.debug("%s -------" % self.__class__.__name__)
    super(FormClass,self).__init__(*args,**kwargs)
    for field in self.fields:
        logger.debug("field of type %s" % type(field))
        if type(field) == BooleanField:
            logger.debug('YES BOOLEAN')
            field.widget = RadioSelect(choices=self.TN_CHOICES)

but it does nothing. In debug log I see every field type is str. How to determine associated model field type?

Lord_JABA
  • 2,545
  • 7
  • 31
  • 58

4 Answers4

3

I believe the problem is that a form's fields attribute appears to act like a dict. Iterating over that gives you only the fieldnames, which are strings.

Instead try

for name, field in self.fields.items():
    ...

This will bind the field variable to the actual field.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
1

Thanks holdenweb - your solution is working. In the meantime I figured out my own alternative

def __init__(self, *args, **kwargs):
    super(FormClass,self).__init__(*args,**kwargs)
     for field_name in self.fields:
         if type(self.fields[field_name])==BooleanField:
             self.fields[field_name].widget = RadioSelect(choices=self.YN_CHOICES)
Lord_JABA
  • 2,545
  • 7
  • 31
  • 58
0

self.fields is a dictionary. When you iterate through a dictionary, you get the keys, which here are strings. You could iterate through self.fields.values() to fix this.

However there is a much simpler way, which is to use the widgets attribute in the modelform's Meta class.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Using @Lord_JABA answer, I personally used the following code to check the type of the form field (here I check for DateField):

def __init__(self, *args, **kwargs):
    super(FormClass, self).__init__(*args, **kwargs)
  
    

    for name, field in self.fields.items():
        str_representation = str(field)
        if "DateField" in str_representation:
            # do something if the field is a DateField