You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I followed the documentation on how to use the ModelSelect2TagWidget, but when I submit the form I get "Select a valid choice error" on the tag field regardless the tag is saved in the database.
models.py
class FromTo(models.Model):
from_to = models.CharField(max_length=100)
class Course(models.Model):
from_to = models.ForeignKey(
FromTo, null=True, on_delete=models.SET_NULL)
forms.py
class FromToWidget(s2forms.ModelSelect2TagWidget):
queryset = models.FromTo.objects.all()
search_fields = ['from_to__icontains']
def value_from_datadict(self, data, files, name):
values = super().value_from_datadict(data, files, name)
queryset = self.get_queryset()
pks = queryset.filter(
**{'pk__in': [v for v in values if v.isdigit()]}).values_list('pk', flat=True)
cleaned_values = []
for val in values:
if represent_int(val) and int(val) not in pks or not represent_int(val) and force_text(val) not in pks:
val = queryset.create(from_to=val).pk
cleaned_values.append(val)
return cleaned_values
class CourseModelForm(forms.ModelForm):
from_to = forms.ModelChoiceField(
models.FromTo.objects.all(), widget=FromToWidget(model=models.FromTo))
Activity