[Answered ]-Get an error while applying a widget to a field

1đź‘Ť

âś…

Just don’t add Select widget to this field, it’s ModelChoiceField, and is rendered as select box anyway. If you put Select widget on ModelChoiceField, it won’t render properly (will show unicode output in value rather than ID).

Also you don’t need the first CharField unless you want a text input with auto-completion.

To show the input element with custom attributes, use {% field %} tag:

{% field myform.myselect class="XYZ" %}

renders it to

<select name="..." class="XYZ">...

I think you’ll agree that it’s a bad idea to customize classes and templates inside forms or models. It makes it impossible to debug templates.

👤culebrón

1đź‘Ť

I ran into a similar problem.

I specified a custom “form” kwarg in a modelformset_factory constructor. This would consistently fail with the error you describe while that form class had custom widgets specified in its meta class:

class MyForm(forms.ModelForm):
  class Meta:
    model = MyModel
    widgets = {
        'myField' : forms.fields.TextInput(attrs={'readonly':'readonly'}),
    }

MyFormFactory = modelformset_factory(MyModel,form=MyForm)

Changing the form class to specify custom widgets in the init method seemed to solve this:

class MyForm(forms.ModelForm):
  class Meta:
    model = MyModel
  def __init__(self,*args,**kwargs):
    self.fields['myField'].widget = forms.fields.TextInput(attrs={'readonly':'readonly'})
👤trubliphone

Leave a comment