Проблемы с сохранением в части формы, зависящей от выпадающего списка

У меня проблема с зависимым выпадающим списком. Во фронтенде он работает отлично и фильтрует меня оптимально, но в бекенде у меня проблемы с сохранением.

Выбрана допустимая опция. Сделанный выбор не входит в число доступных.

Эта ошибка связана с тем, что в form.py я не могу найти 'gruppo_single' в self.data, потому что он был исключен из формы, чтобы динамически передаваться из представления во время поста.

Может ли кто-нибудь помочь мне с этой проблемой?

мои модели

class Gruppi(models.Model):
  nome_gruppo = models.CharField(max_length=100)

class Esercizi(models.Model):
  nome_esercizio = models.CharField(max_length=100) 
  gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'gruppo')

class Schede(models.Model):
  nome_scheda = models.CharField(max_length=100)
  data_inizio = models.DateField()
  data_fine = models.DateField()
  utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente')
  
class DatiGruppi(models.Model):
  giorni_settimana_scelta = [
    ("LUNEDI","Lunedì"),
    ("MARTEDI","Martedì"),
    ("MERCOLEDI","Mercoledì"),
    ("GIOVEDI","Giovedì"),
    ("VENERDI","Venerdì"),
    ("SABATO","Sabato"),
    ("DOMENICA","Domenica")
  ]
  giorni_settimana = MultiSelectField(choices = giorni_settimana_scelta,default = '-')
  dati_gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo')
  gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda')


class DatiEsercizi(models.Model):
  serie = models.IntegerField()
  ripetizione = models.IntegerField()
  peso = models.DecimalField(max_digits = 4,decimal_places = 1,blank = True,null = True)
  dati_esercizio = models.ForeignKey(Esercizi,on_delete = models.CASCADE,related_name = 'dati_esercizio')
  gruppo_single = models.ForeignKey(DatiGruppi, on_delete = models.CASCADE, related_name = 'gruppo_single')

просмотр для создания групп и упражнений

def creazione(request, nome):
    scheda = get_object_or_404(Schede, nome_scheda = nome)
    eserciziFormSet = formset_factory(EserciziForm, extra = 1)
    
    if request.method == "POST":
        
        #form con dati post
        gruppo_form = GruppiForm(request.POST, prefix = 'gruppo')
        esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi')

        #gruppi
        if gruppo_form.is_valid() and esercizi_formset.is_valid():
            gruppo = gruppo_form.save(commit = False)
            gruppo.gruppi_scheda = scheda
            gruppoName = gruppo_form.cleaned_data['dati_gruppo']
            gruppo.save()

            for esercizi in esercizi_formset:
                esercizi_instance = esercizi.save(commit = False)
                esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName)
                esercizi_instance.save()

            return HttpResponseRedirect(request.path_info)

    else:
        gruppo_form = GruppiForm(prefix = 'gruppo')
        esercizi_formset = eserciziFormSet(prefix='esercizi')

    context = {'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset}
    return render(request, 'crea/passo2.html', context) 

просмотр для ajax

def caricamento_esercizi(request):
    gruppo_id = request.GET.get('gruppo')
    esercizi_add = Esercizi.objects.filter(gruppo_id = gruppo_id)
    context = {'esercizi_add': esercizi_add}
    return render(request, 'filtro_esercizi.html', context)

форма для создания упражнений (с реализацией 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)
Вернуться на верх