gpt4 book ai didi

Django根据另一个字段表单更新表单

转载 作者:行者123 更新时间:2023-12-05 06:44:17 25 4
gpt4 key购买 nike

我有以下 Django 表单:

label = forms.CharField(label="Label",
min_length=2,
max_length=100,
required=True,
widget=forms.TextInput(attrs={'class': 'form-control input-sm'}))

hour = forms.ChoiceField(label="Hour",
choices=choice_hour,
required=True,
widget=forms.Select(attrs={'class': 'form-control input-sm'}))

minute = forms.ChoiceField(label="Minute",
choices=choice_minute,
required=True,
widget=forms.Select(attrs={'class': 'form-control input-sm'}))

period = forms.MultipleChoiceField(label="Day of week",
choices=choice_period,
required=True,
error_messages={'required': 'At least you must select one day'},
widget=forms.CheckboxSelectMultiple(renderer=HorizontalCheckboxRenderer))


snooze = forms.ChoiceField(label="Auto stop",
choices=choice_snooze,
required=True,
widget=forms.Select(attrs={'class': 'form-control input-sm'}))


mode = forms.ChoiceField(label="Mode",
choices=choice_mode,
required=True,
widget=forms.Select(attrs={'class': 'form-control input-sm'}))

if mode == 'music':
webradio = forms.ModelChoiceField(queryset=Webradio.objects.all(),
widget=forms.Select(attrs={'class': 'form-control input-sm'}), required=False)
else:
webradio = forms.ModelChoiceField(queryset=Webradio.objects.all(),
widget=forms.Select(attrs={'class': 'form-control input-sm'}), required=True)

class Meta:
model = Alarmclock
fields = ['label', 'hour', 'minute', 'period', 'snooze', 'mode', 'webradio']

“模式”字段形式允许知道用户是想要“ radio ”还是“音乐”。

当Mode为'music'时,webradio字段可以为空。但是当 Mode 为 'radio' 时,必须设置 webradio 字段。

如何根据模式更新 webradio 字段表单?

我尝试使用 IF 条件,但我认为未找到模式变量,webradio 字段一直是必需的。

谢谢。

最佳答案

将webradio字段定义为不需要,然后在clean方法中进行验证(clean的目的是对相互依赖的字段进行验证)。

class Form(forms.ModelForm):

# other fields ...

mode = forms.ChoiceField(
label="Mode", choices=choice_mode, required=True,
widget=forms.Select(attrs={'class': 'form-control input-sm'})
)
webradio = forms.ModelChoiceField(
queryset=Webradio.objects.all(),
widget=forms.Select(attrs={'class': 'form-control input-sm'}),
required=False
)

class Meta:
model = Alarmclock
fields = ['label', 'hour', 'minute', 'period', 'snooze', 'mode', 'webradio']

def clean(self):
mode = self.cleaned_data.get('mode')
if mode == 'music':
webradio = self.cleaned_data.get('webradio')
if not webradio:
raise forms.ValidationError({'webradio': 'Webradio field is required.'})

查看 the docs了解更多详情。

请注意,此方法在 Django 1.7 中已更改:

In previous versions of Django, form.clean() was required to return a dictionary of cleaned_data. This method may still return a dictionary of data to be used, but it’s no longer required.

关于Django根据另一个字段表单更新表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com