user16476339
user16476339

Reputation:

Django search bar and capital letters

I am writing a 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, querying 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 querying 'items'. If you want me to paste more code, just write it.

Upvotes: 2

Views: 489

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

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].

Upvotes: 1

Related Questions