保存在表单部分的下拉依赖问题

Dropdown dependent problems with saving in the form part

我在依赖下拉菜单时遇到问题。 在前端,它工作得很好,并以最佳方式过滤我,但在后端,我在保存时遇到了问题。

Choose a valid option. The choice made does not appear among those available.

这个错误是因为在 form.py 中我找不到 'gruppo_single' 在 self.data 中,因为它被排除在表单之外,以便在 [= =24=].

谁能帮我解决这个问题?

用于创建练习(使用 ajax 实现)和组的表格

class EserciziForm(forms.ModelForm):

    class Meta:
        model = models.DatiEsercizi
        exclude = ['gruppo_single']
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['dati_esercizio'].queryset = models.Esercizi.objects.none()

        if 'gruppo_single' in self.data:
            gruppo_id = int(self.data.get('gruppo'))
            self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id)

        else:
            print("-----errore------")
    


class GruppiForm(forms.ModelForm):

    class Meta:
        model = models.DatiGruppi
        exclude = ['gruppi_scheda']

这就是解决方案。

class EserciziForm(forms.ModelForm):

    class Meta:
        model = models.DatiEsercizi
        exclude = ['gruppo_single']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['dati_esercizio'].queryset = models.Esercizi.objects.none()

        if 'gruppo-dati_gruppo' in self.data:
            gruppo_id = int(self.data.get('gruppo-dati_gruppo'))
            self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id)