How to create a charfield with suggestions in django forms?
I want to create a charfield input in a django form that has suggestions. Essentially I want a choice field that also allows you to write your own value if needed. In other words a hybrid between a charfield and choice field input. Any suggestions on how to achieve this ?
class PDFClassificationForm(forms.ModelForm):
nature = forms.CharField(required=False)
class Meta:
model = Documents
fields = [,
'nature',]
labels = {,,
'nature':'Nature/Concerne:',
}
widgets = {
'dateenvoi' : DatePickerInput(),
}
def __init__(self, uuid_pdf, *args, **kwargs):
super(PDFClassificationForm, self).__init__(*args, **kwargs)
if Documents.objects.get(uuid=uuid_pdf).id_emetteur:
nature_choices= Archivagerecurrencelibelle.objects.filter(Q(id_emetteur=Documents.objects.get(uuid=uuid_pdf).id_emetteur) & Q(source="Nature")).values_list('concerne','concerne')
self.fields['nature'].choices = nature_choices
You might try with this https://github.com/jazzband/django-taggit I used it in a similar use case, you can pass a whitelist of "tags" as suggestion or populate it with already used tags, while still allowing the creation of new values
----------- models.py -------
from django.db import models
ct = (('Ahmedabad','Ahmedabad'),('Surat','Surat'),('Vadodara','Vadodara'),('Rajkot','Rajkot'))
class EmployeeModel(models.Model):
name = models.CharField(max_length=255)
age = models.PositiveIntegerField()
city = models.CharField(max_length=255,choices=ct)
def __str__(self):
return self.name
----------- form.py -------
from django import forms
from .models import EmployeeModel
class EmployeeFrom(forms.ModelForm):
class Meta:
model = EmployeeModel
fields = "__all__"
widgets = {
'name':forms.TextInput(attrs={'class':'form-control'}),
'age':forms.NumberInput(attrs={'class':'form-control'}),
'city':forms.Select(attrs={'class':'form-select'}),
}
----------- Html code for form -----------
<div class="modal-body">
<form action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<label class="form-label">{{form.name.label}}</label>
{{form.name}}
</div>
<div class="mb-3">
<label class="form-label">{{form.age.label}}</label>
{{form.age}}
</div>
<div class="mb-3">
<label class="form-label">{{form.city.label}}</label>
<input class="form-select" placeholder="--- Select city ---" name="city" type="text" list="cities">
<datalist id="cities">
{% for i in form.city %}
<option>{{i}}</option>
{% endfor %}
</datalist>
</div>
<button class="btn btn-primary" type="submit">Add Employee</button>
</form>
</div>
========= Ouput ===============
all cities
after entering keyword