我的表单中有一个我想要隐藏的ModelChoiceField。为此,我将小部件设置为forms.HiddenInput()
。但是,只要窗口小部件设置为forms.HiddenInput()
,该字段就不会验证。我收到验证错误(Hidden field location_choices) Enter a list of values.
当我的所有其他代码都相同时,但我将ModelChoiceField小部件保留为默认值,表单验证正常。
这是我的代码。未验证的字段是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']