Auto complete foreignKey in Django


If you want to add autocomplete field or autocomplete search field in Django forms its pretty easy,

there are a lot of existing packages that can help you with that,

the one that we gonna use is: django-ajax-selects.


Activate your development environment and type the following command:

pip install django-ajax-selects


After installing the package create file called ‘’ in your application directory and add the following to it:

# yourapp/
from ajax_select import register, LookupChannel
from .models import Tag

class TagsLookup(LookupChannel):

    model = Tag

    def get_query(self, q, request):
        return self.model.objects.filter(name__icontains=q).order_by('name')[:50]

    def format_item_display(self, item):
        return u"<span class='tag'>%s</span>" %

and then in your form

#           args:  this model, fieldname on this model, lookup_channel_name
    group = make_ajax_field(Tag, 'group', 'tags', show_help_text=True, required=True)

and in your template add the following:

{{ }}

If you have any question write it in the comments section 🙂


اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *