Goun2
Goun2

Reputation: 437

How to use Django-autocomplete-light for foreign key in the admin

I've been struggling to add an autocomplete to django admin fk fields, I've come across this third party app, Django-autocomplete-light, but its docs are very confusing for beginner like me.

So, I have my model, and how could I add an autocomplete for the fk fields.

Class Order(models.Models)
   Client = models.ForeignKey(settings.AUTH_USER_MODEL)

Upvotes: 2

Views: 3748

Answers (1)

palamunder
palamunder

Reputation: 2745

You should take a look at the documentation and try to read it slowly. If you give more details, about what is not working for you, maybe we could help better. In general, this is what is needed:

In your views.py file add

from django.contrib.auth.models import User
from dal import autocomplete
from your_countries_app.models import Country


class ClientAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !
        if not self.request.user.is_authenticated():
            return User.objects.none()

        qs = User.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

Then in your urls.py file add:

from your_countries_app.views import ClientAutocomplete

urlpatterns = [
    url(
        r'^client-autocomplete/$',
        ClientAutocomplete.as_view(),
        name='client-autocomplete',
    ),
]

Let's skip for a second the part with the shell from the documentation, if it is confusing for you. So now you should be able to go to this address from your browser.

localhost:8000/client-autocomplete/

You should be able to see all the users in a text form there (this format is called JSON, you could look it up, if you want to, but we will not deal with it). If you have created another application for the orders, and you are working in another folder, just try to call the url with the orders as prefix instead:

localhost:8000/orders/client-autocomplete/

Browser view

I suppose that you are familiar with the forms in Django, if not take a look here. In your forms.py add this:

from dal import autocomplete
from django.contrib.auth.models import 
from django import forms


    class OrderForm(forms.ModelForm):
        client = forms.ModelChoiceField(
            queryset=User.objects.all(),
            widget=autocomplete.ModelSelect2(url='cllient-autocomplete')
            # if you are working in an orders application, and you have defined the the url 
            #in the orders/urls.py then call this method like this:
            #widget=autocomplete.ModelSelect2(url='orders:cllient-autocomplete')

        )

        class Meta:
            model = Order
            fields = ('__all__')

I suppose you want the autocomplete to be working outside of the admin panel views, so you have to your template for the orders view add the code below. Please, notice that you should have in your base.html the {% block content %} and the {% block footer %} defined:

{% extends 'base.html' %}
{# Don't forget that one ! #}
{% load static %}

{% block content %}

<div>
    <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" />
    </form>
</div>
{% endblock %}

{% block footer %}
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>

{{ form.media }}
{% endblock %}

Upvotes: 5

Related Questions