1

Django search bar and capital letters

Hello i am making Django app and I have a question. I have made a search bar. Everything would work correctly as I want but the problem is when the Item has capital letter or vice versa, quering does not work as I would like to. I wanted to make it search for the item when it is written 'tea' or 'TEA' or 'TeA'. I hope you understand me. :)

Code:

views.py
  def searchView(request):
    if request.method == "GET":
        context = request.GET.get('search')
        items = Item.objects.all().filter(title__contains=context)

urls.py:

     urlpatterns = [
    path('', ShopListView.as_view(), name='home-page'),
    path('signup', views.signup, name='signup-page'),
    path('login', views.loginView, name='login-page'),
    path('logout', views.logoutView, name='logout-page'),
    path('detail/<int:pk>/', ShopDetailView.as_view(), name='detail-page'),
    path('search/', views.searchView, name='search-page')
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I think here is an issue in quering 'items'. If you want me to paste more code, just write it.

Submitted August 22nd 2021 by Admin

Answers
0

You can filter with the __icontains [Django-doc] to make a case-insensitive match:

from django.views.decorators.http import require_GET @require_GET
def searchView(request): if 'search' in request.GET: context = request.GET['search'] items = Item.objects.filter(title__icontains=context) else: items = Item.objects.none() return render(request, 'shop/search.html', {'items': items})

You likely should return something in case the search parameter is not passed. For example, an empty page.


Note: You can limit views to GET requests with the @require_GET decorator [Django-doc].

Admin | 1 month ago



Relevant Questions