Search code examples
djangodjango-autocomplete-light

django-autocomplete-light with crispy forms


I am trying to implement an autocomplete search on a foreignkey field in my form. I have been through the docs but not sure what I need to do to get it working. I just get the normal dropdown box on the foreignkey field.

Here is my attempt:

settings.py

INSTALLED_APPS = (
    'crispy_forms',
    'autocomplete_light',
)

urls.py

url(r'^autocomplete/', include('autocomplete_light.urls')),

models.py

class Client(models.Model):
    ...

class Branch(models.Model):
    client = models.ForeignKey(Client, related_name='clients')
    ...

forms.py

import autocomplete_light

class BranchForm(autocomplete_light.ModelForm):
    class Meta:
        model = Branch
        autocomplete_fields = ('client')
        exclude = ('creation', 'last_modified')

form.html

 <form method="POST" action="">{% csrf_token %}
                            {{ form|crispy }}
                            <input class="btn btn-primary" type="submit" value="Submit" />
                            <a href="{% url 'branch' %}"><button type="button" class="btn btn-danger">Cancel</button></a>
                        </form>

Solution

  • Figured it out in the end. Needed to register it.

    autocomplete_light.register(Branch,
               name = 'ClientAutocomplete',
               choices = Client.objects.all()
           )
    
           class ClientForm(forms.ModelForm):
               class Meta:
                   model = Client
                   exclude = ('creation', 'last_modified')
    
    
           class BranchForm(autocomplete_light.ModelForm):
               class Meta:
                   model = Branch
                   autocomplete_names = {'client':'ClientAutocomplete'}
                   exclude = ('creation', 'last_modified')