How to assign a class to a field type in Django?

Asked

Viewed 66 times

1

I’m trying to figure out which field is a DateField and thereby assign a class='date'. How do I know the guy from the field?

The following code does not work but presents the logic:

class MeuForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(MeuForm, self).__init__(*args, **kwargs)            
        for field_name, field in self.fields.items():                
            if field == "DateField": # (exemplo) como saber que é um DateField?
                field.widget.attrs['class'] = 'date'
  • self.fields['DateField'].widget.attrs['class'] = 'date' would not work in this case?

  • 1

    @Qmechanic73 that way I would have to assign 'date' for each field, the way I asked I assign at once to all type Fields DateField.

1 answer

2


Use isinstance:

for field_name, field in self.fields.items():                
    if isinstance(field, forms.DateField):
        field.widget.attrs['class'] = 'date'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.