user16375265
user16375265

Reputation:

Django How to make the condition correct on an HTML page - search bar

I try to do a search engine if the word in my DB thah I created then display the word on the HTML page and if not then nothing.. I did it right in VIEW but I can not apply it on the HTML page I searched the internet and did not find an answer I'm sure I fall for something stupid.

This is the view

def Search_word(request):
search = request.POST.get("search")  #Grab the search item
return render(request,"search_page.html", {"search":search})

this is the html:

{%for i in Word.English_word%}

{%if search in Word.English_word%}

{{search}}

{%endif%} {%endfor%}

and the urls:

    path("Search_page",views.Search_word ,name="Search-page"),

models:

class Words(models.Model):
English_word = models.CharField(max_length=30)
Hebrew_word = models.CharField(max_length=30)
How_To_Remember = models.CharField(max_length=40)
Name = models.CharField(max_length=20)
pub_date = models.DateTimeField()

The problem is that even if the word is valid it does not show me anything ..

Upvotes: 2

Views: 46

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477230

You should implement the filtering logic in the view, not in the template. Templates are for rendering logic, not business logic. Furthermore one should filter with the database, since databases are designed to do this.

The view thus looks like:

def Search_word(request):
    search = request.POST.get('search')
    items = Word.objects.filter(English_word__contains=search)
    return render(
        request,
        'search_page.html',
        {'search': search, 'items': items}
    )

and then in the template we render this with:

{% for item in items %}
    {{ item.English_word }}: {{ item.Hebrew_word }} <br>
{% endfor %}

You can use as lookup __contains to check if the English_word has a substring that is equal to search, with __icontains you check case-insensitive, with __iexact you look for Words that match search case-insensitive, and finally you can filter with Engish_word=search for an exact match.

Upvotes: 1

Related Questions