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

时间:2022-11-23 11:41:38

I have the following Django form :

我有以下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']

The 'Mode' field form permit to know if user want 'Radio' or 'Music'.

“Mode”字段表单允许用户知道用户想要“Radio”还是“Music”。

When the Mode is 'music', webradio field can be empty. But when the Mode is 'radio' , webradio field must be set.

当模式为“music”时,webradio字段可以为空。但是当模式为“radio”时,必须设置webradio字段。

How I can update the webradio field form according to the mode ?

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

I tried with a IF condition, but I think the mode variable is not found, the webradio field is all the time required.

我尝试了一个IF条件,但是我认为没有找到模式变量,webradio字段是所有需要的时间。

Thanks.

谢谢。

2 个解决方案

#1


1  

Define webradio field as not required and then do the validation in the clean method (purpose of clean is to do validation of fields that rely on each other).

定义不需要的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.'})

Check out the docs for more details.

查看文档了解更多细节。

Note that this method has changed in Django 1.7:

请注意,这个方法在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的以前版本中,需要form.clean()返回一个cleaned_data字典。此方法仍然可以返回要使用的数据字典,但不再需要。

#2


0  

I guess this should do the trick.

我想这应该能奏效。

class FormName(forms.ModelForm):

    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'}))

    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']

    def clean_mode(self):
        mode = self.cleaned_data.get('mode')
        if mode == 'music':
            self.fields['webradio'].required = False
        return super(FormName,self).clean_mode()

What it does basically is change the required attribute of the webradio field on the go, depending upon the value of mode.

它所做的基本上是根据模式的值在运行时更改webradio字段的required属性。

#1


1  

Define webradio field as not required and then do the validation in the clean method (purpose of clean is to do validation of fields that rely on each other).

定义不需要的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.'})

Check out the docs for more details.

查看文档了解更多细节。

Note that this method has changed in Django 1.7:

请注意,这个方法在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的以前版本中,需要form.clean()返回一个cleaned_data字典。此方法仍然可以返回要使用的数据字典,但不再需要。

#2


0  

I guess this should do the trick.

我想这应该能奏效。

class FormName(forms.ModelForm):

    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'}))

    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']

    def clean_mode(self):
        mode = self.cleaned_data.get('mode')
        if mode == 'music':
            self.fields['webradio'].required = False
        return super(FormName,self).clean_mode()

What it does basically is change the required attribute of the webradio field on the go, depending upon the value of mode.

它所做的基本上是根据模式的值在运行时更改webradio字段的required属性。