How do you add a widget to a form field in init in django?
Basically, I want to change a form field's widget in the init function. First of all, here is the form:
class ModelForm(forms.ModelForm):
date = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(ModelForm, self).__init__(*args, **kwargs)
self.fields['date'].choices = DATE_CHOICES
class Meta:
model = Model
fields = (
'date',
)
widgets = {'date': SelectDateWidget()}
However, the widget SelectDateWidget()
didn't seem to work for some reason. So, I want to instead add this widget to the init function so that the widget would be reflected on the form. However, this is just my thought. If adding this widget to the init function will not work, could you please give me some way to use this widget for the date
field? Thank you, and please leave me any questions you have.
If we assume that the date is a DateField
, then you can add the SelectDateWidget
like this :
class ModelForm(forms.ModelForm):
date = forms.DateField(widget=forms.SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day"),))
class Meta:
model = Model
fields = (
'date',
)
Now if you want to add some defined choices then follow this link for more details.
The doc here is also good to read.
NB : You not have to override the__init__
method for that.