Python Django多值字段可选字段
我已经搜索了所有地方,我能找到的都是几年前的东西和/或不适用的东西 我试图在表单中添加一个多值字段,这样人们就可以轻松地输入一到三个输入。应该只需要这些字段中的第一个,但是表单验证器仍然需要这三个字段,除非我将整个内容设置为可选(不应该是可选的) 下面是我的多窗口小部件、多值字段和表单的代码。我尝试从字段属性中删除除Python Django多值字段可选字段,python,django,django-forms,Python,Django,Django Forms,我已经搜索了所有地方,我能找到的都是几年前的东西和/或不适用的东西 我试图在表单中添加一个多值字段,这样人们就可以轻松地输入一到三个输入。应该只需要这些字段中的第一个,但是表单验证器仍然需要这三个字段,除非我将整个内容设置为可选(不应该是可选的) 下面是我的多窗口小部件、多值字段和表单的代码。我尝试从字段属性中删除除required=False之外的所有属性,但仍然需要所有属性。我尝试在调用字段时在表单中设置require\u all\u fields=False,而不是在字段中设置requir
required=False之外的所有属性,但仍然需要所有属性。我尝试在调用字段时在表单中设置require\u all\u fields=False
,而不是在字段中设置require\u init\u
,但它仍然需要所有字段
我觉得我已经读了又读,关于如何实现这类事情的信息很少
class ThreeNumFields(forms.MultiWidget):
def __init__(self, attrs=None):
self.widgets = [
forms.TextInput(),
forms.TextInput(),
forms.TextInput()
]
super().__init__(self.widgets, attrs)
def decompress(self, value):
if value:
return value.split(' ')
return [None, None]
class LocationMultiField(forms.MultiValueField):
widget = ThreeNumFields()
validators = [RegexValidator]
def __init__(self):
fields = (
forms.CharField(
error_messages={'incomplete': 'Please enter at least one valid zip code.'},
validators=[
RegexValidator(r'^[0-9]{5}$', 'Enter a valid US zip code.'),
],
max_length=5,
),
forms.CharField(
required=False,
validators=[
RegexValidator(r'^[0-9]{5}$', 'Enter a valid US zip code.'),
],
max_length=5,
),
forms.CharField(
required=False,
validators=[
RegexValidator(r'^[0-9]{5}$', 'Enter a valid US zip code.'),
],
max_length=5,
)
)
super(LocationMultiField, self).__init__(
fields=fields,
require_all_fields=False,
)
def compress(self, data_list):
return ' '.join(data_list)
class NewForecastForm(forms.ModelForm):
class Meta:
model = ForecastProfile
exclude = ['userid', 'last_updated']
nickname = forms.CharField(
label=_('Forecast Nickname')
)
locations = LocationMultiField()
timezone = forms.ChoiceField(
label=_('Timezone for your forecast'),
choices=choices.timezones
)
start_time = forms.ChoiceField(
label=_('Earliest time you want in your forecast'),
help_text=_('(Time will not be exact to account for timezone conversions and forecast data.)'),
choices=choices.times
)
end_time = forms.ChoiceField(
label=_('Latest time you want in your forecast'),
help_text=_('(Time will not be exact to account for timezone conversions and forecast data.)'),
choices=choices.times
)
alerts = forms.MultipleChoiceField(
choices=choices.alerts,
widget=forms.CheckboxSelectMultiple()
)
days_in_forecast = forms.ChoiceField(
choices=choices.forecastdays
)
def clean(self):
cleaned_data = super(NewForecastForm, self).clean()
start = cleaned_data.get("start_time")
end = cleaned_data.get("end_time")
if start > end:
raise forms.ValidationError(
"Your start time must be before your end time."
)
我遇到了同样的问题,它看起来像是Django的一个bug。有一张公开票
也就是说,在我的例子中,通过设置required=False
,require\u all\u fields=False
,并在表单的init方法中将required显式添加到小部件属性中,我确实使表单正常工作
在您的情况下,这意味着在NewForecastForm的init方法中放入self.fields['locations'].widget.widgets[0].attrs['required']=True