Search code examples
djangotypeerrordjango-formsdjango-widget

__init__() got an unexpected keyword argument 'widget'


I'm trying to run web app page which uses the below form;

class InputParametersForm(ModelForm):

    sqlConnection = SQLSeverConnection(
        'MSSQLServerDataSource',
        'default_user',
        'password123!!',
        'HD'
    )
    tableChoices = sqlConnection.getTableNames()
    TableName = forms.Select(
        widget=forms.Select(attrs={'class': 'selector'})
    )
    ColumnName = forms.Select(
        widget=forms.Select(attrs={'class': 'selector'})
    )
    StartDateTime = forms.DateField(
        widget=SelectDateWidget(
            empty_label=("Choose Year", "Choose Month", "Choose Day")
        )
    )
    EndDateTime = forms.DateField(
        widget=SelectDateWidget(
            empty_label=("Choose Year", "Choose Month", "Choose Day")
        )
    )

    class Meta:
        model = SelectionHistory
        fields = ("TableName", "ColumnName", "StartDateTime", "EndDateTime")

When I run manage.py runserver and go to the local URL I'm getting a 500 page with the error __init__() got an unexpected keyword argument 'widget' where I've tried to use the widget.

This is probably some basic error I'm making but if somebody could point me in the right direction it'd be a big help - preferably with some code.


Solution

  • forms.Select is a widget, it is not a Field and it doesn't have a widget argument. This is what the error is reporting about. This is what you basically have:

    >>> from django import forms
    >>> forms.Select(widget=forms.Select)
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    TypeError: __init__() got an unexpected keyword argument 'widget'
    

    Instead, you meant to have a ChoiceField with a Select widget:

    TableName = forms.ChoiceField(widget=forms.Select(attrs={'class': 'selector'}))
    

    See also Daniel's example here: