[Answered ]-Apply a filter to the choices field of my model

1👍

You can let the PianoSingleDayForm exclude the days that have already been selected for that Piano with:

class PianoSingleDayForm(forms.ModelForm):
    def __init__(self, *args, piano=None, **kwargs):
        super().__init__(*args, **kwargs)
        if piano is not None:
            days = set(PianoDaySingle.objects.filter(
                single_piano=piano
            ).values_list('giorni_settimana', flat=True))
            self.fields['giorni_settimana'].choices = [
                (k, v)
                for k, v in self.fields['giorni_settimana'].choices
                if k not in days
            ]

    class Meta:
        model = models.PianoSingleDay
        exclude = ['single_piano']

We can then use this in the view by passing the Piano object to the form both in the GET and POST codepath:

@login_required
def PianoSingleView(request, id):
    piano = get_object_or_404(models.Piano, id=id, utente_piano=request.user)
    if request.method == 'POST':
        giorno_form = PianoSingleDayForm(request.POST, piano=piano, prefix='giorno')
        if giorno_form.is_valid():
            giorno_form.instance.single_piano = piano
            giorno_form.save()
            return redirect('gestione-piano', id=piano.id)
    else:
        giorno_form = PianoSingleDayForm(piano=piano, prefix='giorno')
    
    context = {'piano': piano, 'giorno_form': giorno_form}
    return render(request, 'crud/create/gestione_piano_single.html', context)

Leave a comment