I am trying to have a field in a form that allows users to select objects from a Model and also allows free text input. I am using django-autocomplete-light. Although it works great for selecting choices from the model, I can't get it to allow free text input without creating new objects before the form is submitted.
Before someone marks this as duplicate, I did read this question but it did not guide me into a solution.
Here's my models.py:
class Person(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
My forms.py:
class NameForm(forms.ModelForm):
name = forms.ModelChoiceField(
queryset=Person.objects.all(),
widget=autocomplete.ModelSelect2(url='myapp:name-autocomplete')
)
class Meta:
model = Person
fields = ['name',]
My views.py:
class PersonAutoComplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = Person.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
And my urls.py:
path(
'name-autocomplete/',
PersonAutoComplete.as_view(create_field='name'),
name='name-autocomplete',
),