'Diacritics in search function case sensitive
I have a search function in my Django app:
#search
def search(request):
if request.method == "POST":
searched = request.POST['searched']
result = Post.objects.filter(title__contains=searched)
return render(request, 'blog/searched.html', {'searched':searched, 'result':result})
else:
return render(request, 'blog/searched.html',{})
Problem is, when I search the following, I get the following results:
Zaštita -> I get 'Zaštita' result
zaštita -> I get 'Zaštita' result
Čep -> I get 'Čep' result
čep -> I get nothing (diacritic letter in the first place, case sensitive)
Only if diacritic letter in the first place the search is case sensitive.
Input page HTML:
<div class="content-section">
<form class="d-flex" method=POST action="{% url 'search' %}">
{% csrf_token %}
<input class="form-control me-2 mr-2" type="search" placeholder="Title" aria-label="Search" name="searched">
<button class="btn btn-outline-secondary" type="submit">Search</button>
</form>
</div>
Solution 1:[1]
You can use the __icontains lookup [Django-doc] to make a case insenstive search. Normally searching is however done through a GET request: POST requests are usually used for state-changing actions, or when submitting sensitive data.
You thus can search with:
def search(request):
searched = request.GET.get('searched')
result = Post.objects.all()
if searched is not None:
result = result.filter(title__icontains=searched)
return render(request, 'blog/searched.html', {'searched':searched, 'result':result})
Note: While using the
__icontainslookup [Django-doc] produces results for text, this often is still a poor way to search, since it will only fetch items with the exact string. Usually one uses solutions like Elastic or Solr, or one can uses PostgreSQL's__searchlookup [Django-doc].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
