Can models have widgets?

I have a DateField thing inside my models.py file. Is it possible to import the widget or something?

due_date = models.DateField('Deadline: ', blank=True, default=datetime.datetime.today, widget=forms.SelectDateWidget())

This doesn’t work because I get this error:
TypeError: __init__() got an unexpected keyword argument 'widget'

It works though if it’s under a class that takes forms.ModelForm as its parameter.

Widgets belong to forms, not to models. You specify a widget on a form field, so that specification belongs there (forms.py), not in your models.py.

1 Like

ModelForm will give you access to the ‘widget’ attribute of the Meta class.

class MyForm(ModelForm):
     class Meta:
          model = MyModel
           fields = ['due_date',] 
           # or any other fields you want on the form
          widgets = {
                'due_date': forms.SelectDateWidget(...)
          }
2 Likes