How to define attributes on forms.ModelChoiceField?

In my ModelForm, I created a drop-down list that is not directly related to anything on the model. Therefore, I pass the request for it after creating the instance.

class CallsForm(ModelForm): def __init__(self, company, *args, **kwargs): super(CallsForm, self).__init__(*args, **kwargs) self.fields['test_1'].queryset = company.deal_set.all() test_1 = forms.ModelChoiceField(queryset = '') 

This works great. However, how do I specify some attributes for this?

For other model-related widgets, I usually do this in a meta tag:

 class Meta: model = Conversation widgets = { 'notes': forms.Textarea(attrs={'class': 'red'}), } 

But redefining this in my case would not make sense.

I tried to set attributes when instantiating with no luck.

 test_1 = forms.ModelChoiceField(attrs={'class':'hidden'}, queryset = '') 

but he says: __init__() got an unexpected keyword argument 'attrs'

Of course, there must be a way ...

+6
source share
1 answer

attrs valid only for widgets, not fields. Try:

 test_1 = forms.ModelChoiceField(queryset = '', widget=forms.Select(attrs={'class':'hidden'})) 
+23
source

Source: https://habr.com/ru/post/921146/


All Articles