title: how to create a autocomplete input field in a form using Django
body: <p>I am pretty new to django and its ways. I am trying to create an autocomplete field for a form. My code is as below</p>
  
  <p><strong>forms.py</strong></p>
  
  <pre><code>from django import forms
  
  class LeaveForm(forms.Form):
      leave_list = (
          ('Casual Leave', 'Casual Leave'),
          ('Sick Leave', 'Sick Leave')
      )
      from_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'style': 'width: 400px'}))
      start_date = end_date = forms.CharField(widget=forms.TextInput(attrs={'type': 'date', 'style': 'width: 175px'}))
      leave_type = forms.ChoiceField(choices=leave_list, widget=forms.Select(attrs={'style': 'width: 400px'}))
      comments = forms.CharField(required=True, widget=forms.Textarea(attrs={'style': 'width: 400px; height: 247px'}))
  
      def clean_from_email(self):
          data = self.cleaned_data['from_email']
          if "@testdomain.com" not in data:
              raise forms.ValidationError("Must be @testdomain.com")
          return data
  </code></pre>
  
  <p>What I want to achieve is that when an user types words into the <code>"From Email"</code> field the list of emails I have stored in an external DB should appear in the autocomplete list option.</p>
  
  <p><strong>models.py</strong></p>
  
  <pre><code>from django.db import models
  
  
  class ListOfUsers(models.Model):
      emp_number = models.CharField(db_column='Emp_Number', primary_key=True, max_length=50, unique=True)  # Field name made lowercase.
      name = models.CharField(db_column='Name', max_length=40)  # Field name made lowercase.
      supervisor = models.CharField(db_column='Supervisor', max_length=40)  # Field name made lowercase.
      email = models.CharField(db_column='Email', max_length=50, blank=False, null=False, unique=True)  # Field name made lowercase.
  
  
      class Meta:
          managed = False
          db_table = 'List of users'
  </code></pre>
  
  <p>Any idea how this can be done ?</p>
  
  <p><strong>Update :</strong></p>
  
  <p>I started messing around with django-autocomplete-light and now able to get a reply from the autocomplete url. It looks like this</p>
  
  <pre><code>{"results": [{"id": "user1@mydomain.com", "text": "user1@mydomain.com"}, {"id": "user2@mydomain.com", "text": "user2@mydomain.com"}, {"id": "user3@mydomain.com", "text": "user3@mydomain.com"}]}
  </code></pre>
  
  <p><strong>views.py</strong></p>
  
  <pre><code>class EmailAutocomplete(autocomplete.Select2ListView):
      def get_list(self):
          qs = ListOfUsers.objects.using('legacy')
  
          if self.q:
              qs = qs.filter(email__icontains=self.q).values_list('email', flat=True)
  
          return qs
  </code></pre>
  
  <p>I still do not know how to get this data to appear in the field <code>"from_email"</code></p>