[Answered ]-How to create a charfield with suggestions in django forms?

1๐Ÿ‘

โœ…

โ€”โ€”โ€”โ€“ models.py โ€”โ€”-

from django.db import models


class EmployeeModel(models.Model):
    name = models.CharField(max_length=255)
    age = models.PositiveIntegerField()
    city = models.CharField(max_length=255)

    def __str__(self):
        return self.name

โ€”โ€”โ€”โ€“ form.py โ€”โ€”-

class EmployeeFrom(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(EmployeeFrom, self).__init__(*args, **kwargs)
        self.fields['city'].widget = forms.Select(choices = CityModel.objects.values_list('name','name'))
        

    class Meta:
        model = EmployeeModel
        fields = "__all__"

        widgets = {

            'name':forms.TextInput(attrs={'class':'form-control'}),
            'age':forms.NumberInput(attrs={'class':'form-control'}),

        }

โ€”โ€”โ€”โ€“ 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

enter image description here

after entering keyword

enter image description here

==== last output ==============

enter image description here

0๐Ÿ‘

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

๐Ÿ‘คgpw

Leave a comment