I have a ModelChoiceField in my form that I want to hide. To do this, I'm setting the widget to forms.HiddenInput()
. However, whenever the widget is set to be forms.HiddenInput()
, the field will not validate. I get the validation error (Hidden field location_choices) Enter a list of values.
When all my other code is the same, but I leave the ModelChoiceField widget as the default, the form validates fine.
Here is my code. The field that is not validating is location_choices:
class SingleSessionForm(forms.ModelForm):
start_time = forms.DateTimeField(widget=SplitDateTimeWidget)
end_time = forms.DateTimeField(widget=SplitDateTimeWidget)
price = forms.IntegerField(
label=_('Price'),
min_value=0,
)
def __init__(self, *args, **kwargs):
super(SingleSessionForm, self).__init__(*args, **kwargs)
self.fields['price'].initial = self.instance.prices[0]
if self.instance.event.studio:
self.fields['location_choices'].widget = forms.HiddenInput()
self.fields['location_choices'].required = False
self.fields['house_calls'].widget = forms.HiddenInput()
self.helper = FormHelper()
self.helper.form_id = 'id-add_sessions'
self.helper.form_class = 'blueForms'
self.helper.layout = Layout(
Fieldset(
'Time',
'start_time',
'end_time',
),
Fieldset(
'Details',
Field(
'location', 'location_choices', 'house_calls'
),
'max_enrollment',
Field(
PrependedAppendedText('price', '$', '.00'),
)
),
FormActions(
Submit('action', 'Submit', css_class='btn btn-primary btn-large'),
Button('cancel', 'Cancel', css_class='btn btn-danger btn-large', onclick="window.location.replace('" + self.instance.get_absolute_url() + "')")
)
)
def clean_location_choices(self):
if self.instance.event.studio:
return self.instance.event.studio.locations
return self.cleaned_data['location_choices']
def clean_allow_home_training(self):
if self.instance.event.studio:
return False
return self.cleaned_data['house_calls']