Hello,
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.
Installation
Activate your development environment and type the following command:
pip install django-ajax-selects
Usage
After installing the package create file called ‘lookups.py’ in your application directory and add the following to it:
# yourapp/lookups.py
from ajax_select import register, LookupChannel
from .models import Tag
@register('tags')
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>" % item.name
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:
{{ form.media }}
{{form.as_p}}
If you have any question write it in the comments section 🙂
اترك تعليقاً