deathangel908
deathangel908

Reputation: 9689

django apply widget for all fields

Is there a way to apply css class to ALL fields instead of doing the following for every single field.
forms.py

class UserColorsForm(forms.ModelForm):

    class Meta:
        model = UserColors
        exclude = ('userid',)
        widgets = {
            'text_color': forms.TextInput(attrs={'class': 'color'}),
            'background_color': forms.TextInput(attrs={'class': 'color'}),
            ... 10 more
        }

Upvotes: 5

Views: 2809

Answers (4)

You can create a list of the fields you want. Then create a function that returns a dictionary using the fields as keys. Lastly, you set the Meta.widgets to call the function you have created.

fields_you_want = [
            'first_name',
            'last_name',
            'other_names',
        ] 


def get_widget_dictionary():

    keys = fields_you_want

    values = [ forms.TextInput(attrs={'class': 'form-control'}) for key in keys ]
    result = dict(zip(keys, values))
    return result


class UserColorsForm(forms.ModelForm):

    class Meta:
        model = UserColors
        widgets = get_widget_dictionary()

Upvotes: 0

  vrnvorona
vrnvorona

Reputation: 476

To update Mihai's answer, the way is:

def __init__(self, *args, **kwargs):
    super(YourForm, self).__init__(*args, **kwargs)
    for field in self.fields:
        self.fields[field].widget.attrs.update({'class': 'myfieldclass'})

Upvotes: 4

James
James

Reputation: 2518

Try to iterate the form fields:

css1 = {'class': 'color', }
css2 = {'class': 'nocolor', }
class UserColorsForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserColorsForm, self).__init__(*args, **kwargs)
        for key, value in self.fields.iteritems():
            if key in ['field1', 'field2', ...]: # You can define a 
                # subset of fields in a list to selectively apply css classes, 
                # OR just iterate and apply to everything 
                # (take out the if-else statement)
                self.fields[key].widget.attrs.update(css1)
            else:
                self.fields[key].widget.attrs.update(css2)

Upvotes: 1

Mihai Zamfir
Mihai Zamfir

Reputation: 2166

This should work

def __init__(self, *args, **kwargs):
    super(UserColorsForm, self).__init__(*args, **kwargs)
    for field in self.fields: 
        field.wiget.attrs['class'] = 'color'

Upvotes: 4

Related Questions