Within my ModelForm I have created a dropdown that isn't bound to anything on the model directly. Hence I pass in the queryset for it upon instantiation.
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 just fine. However how do I specify some attributes for it?
For the other model-bound-widgets I usually do this in Meta:
class Meta:
model = Conversation
widgets = {
'notes': forms.Textarea(attrs={'class': 'red'}),
}
But overriding it in my case would make no sense.
I tried to set the attributes upon instantiation without any luck.
test_1 = forms.ModelChoiceField(attrs={'class':'hidden'}, queryset = '')
but it says: __init__() got an unexpected keyword argument 'attrs'
Surely there must be a way...
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.
Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.
attrs
is only valid on widgets, not fields. Try:
test_1 = forms.ModelChoiceField(queryset = '', widget=forms.Select(attrs={'class':'hidden'}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With