Hello. I already searched on the old posts but i don't find a solution for my problem.
I have the next model :
In views.py :
class TermAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
qs = Term.objects.all()
if self.q:
qs = qs.filter(nom__startswith=self.q)
return qs
In forms.py
class TermForm(forms.ModelForm):
class Meta:
model = Term
fields = ('__all__')
subterms = forms.ModelChoiceField(
queryset=Term.objects.all(),
widget=autocomplete.ModelSelect2Multiple(url='term-autocomplete')
)
and in views.py, my controller
def term_new(request):
if request.method == "POST":
form = TermForm(request.POST)
if form.is_valid():
term = form.save(commit=False)
return redirect('term_new', pk=term.pk)
else:
form = TermForm()
return render(request, 'term_edit.html', {'form': form})
And my model
class Term(models.Model):
nom = models.CharField(max_length=255, verbose_name="Nom du term", db_index=True)
langue = models.CharField(max_length=100, verbose_name="Langue", choices=TYPE_LANG)
lemma = models.CharField(max_length=255, verbose_name="Lemma du term", db_index=True)
subterms = models.ManyToManyField("self", verbose_name="Subterms", blank=True)
When i try to create a new Term, i get the following error :
"select a valid choice. that choice is not one of the available"
But when i change my form using the widgets parameter (without replacing the field), it works :
class TermForm(forms.ModelForm):
class Meta:
model = Term
fields = ('__all__')
widgets = {
'subterms': autocomplete.ModelSelect2Multiple(url='term-autocomplete'),
}
Do you have some idea about what's happening with my code? Actually, i'm not able to replace the field and i need it to add custom validators.
On the other hand, when i try to edit a Term (replacing field code), i get an "invalid int 10" error. But when i use the widgets attribute without replacing the field, i can edit, everything works very fine.
Thank you in advance
Select a valid choice is because your choice pk is not found in the form field queryset.
Did you try:
subterms = forms.ModelMultipleChoiceField
Instead of:
subterms = forms.ModelChoiceField
For your ManyToManyField and ModelSelect2Multiple widget ?
Sounds like it might work better together.
You're right!! Thank you so much! I was using the wrong widget for a M2M relationship
Most helpful comment
Select a valid choice is because your choice pk is not found in the form field queryset.
Did you try:
Instead of:
For your ManyToManyField and ModelSelect2Multiple widget ?
Sounds like it might work better together.