I am trying to make a search field on my homepage where you search entries by tag, and within that search field as you type in letters it should suggest you tags that contain what you have typed so far. I am using django-taggit for tags. I have followed this tutorial : https://django-autocomplete-light.readthedocs.io/en/master/taggit.html It has support for django-taggit.
template
<div class="search-container">
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
<button type="submit">Search</button>
</form>
</div>
urls.py
# AUTOCOMPLETE URL
url(r'^tag-autocomplete/$', views.TagAutocomplete.as_view(), name='tag-autocomplete'),
forms.py
class SearchForm(autocomplete.FutureModelForm):
class Meta:
model = Intrare
fields = ('tags',)
widgets = {
'tags': autocomplete.TaggitSelect2('intrari:tag-autocomplete')
}
models.py
class Intrare(models.Model):
tags = TaggableManager()
def __str__(self):
return self.titlu
views.py
class TagAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
intrari = [intrare.tags for intrare in Intrare.objects.filter(public=True)]
tags = reduce(lambda x, y: x | y, [tags.get_queryset() for tags in intrari])
tags = [tag.name for tag in tags]
qs = Tag.objects.filter(name__in=tags)
if self.q:
qs = qs.filter(name__contains=self.q)
return qs
I have found the mistake, I forgot to add {{ form.media }} in template.
<div class="search-container">
{{ form.media }}
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
<button type="submit">Search</button>
</form>
</div>