Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define attributes on forms.ModelChoiceField?

Tags:

django

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...

like image 788
Houman Avatar asked Jul 23 '12 17:07

Houman


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is forms ModelForm in Django?

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.

What is class Meta in Django forms?

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.


1 Answers

attrs is only valid on widgets, not fields. Try:

test_1 = forms.ModelChoiceField(queryset = '', widget=forms.Select(attrs={'class':'hidden'}))
like image 148
Chris Pratt Avatar answered Oct 24 '22 00:10

Chris Pratt