Lord_JABA
Lord_JABA

Reputation: 2625

Django- How to determine field types in ModelForm init?

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?

Upvotes: 1

Views: 1444

Answers (4)

Haider Ali J Al-Rustem
Haider Ali J Al-Rustem

Reputation: 551

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

Upvotes: 0

Lord_JABA
Lord_JABA

Reputation: 2625

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)

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599580

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.

Upvotes: 0

holdenweb
holdenweb

Reputation: 37023

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.

Upvotes: 3

Related Questions