ApPeL
ApPeL

Reputation: 4911

django modelform css class for select

I am trying to add in a class with the name of autocomplete into one of my select.

class MyForm(ModelForm):
    class Meta:
        model = MyModel
        exclude = ['user']

    def __init__(self, user, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['specie'].queryset = Specie.objects.all(attrs={'class':'autocomplete'})

Based on the code above I get all() got an unexpected keyword argument 'attrs'

Upvotes: 2

Views: 4013

Answers (1)

Manoj Govindan
Manoj Govindan

Reputation: 74705

Edit the existing code as shown below and try again.

self.fields['specie'].queryset = Specie.objects.all()
self.fields['specie'].widget.attrs['class'] = 'autocomplete'

Explanation: the first line sets the queryset for the field, i.e. values to choose from. The right hand side filters all objects of Specie. A HTML/CSS attribute has no relevance here. The second line tells the widget used to render the field to use a specific CSS class.

Upvotes: 7

Related Questions