blacklight
blacklight

Reputation: 130

Django search functionality

I added a search functionality to my website, such that if you goto www.mywebsite.com/search/texthere , it displays all the songs with title=texthere. I would like to add this functionality to my index page.

In my page, there is an input box where users could type the input and the press submit to submit the input but it goes to some another page. How can I solve this?

urls.py

url(r'^search/(?P<query>[\w\-]+)/$', views.search, name='search'),

index.html

<form action="/search/">
     <input type="text"  name="query" value="me"><br>
     <input type = "submit">
</form>

What I want is when the user clicks submit button, the text from the input box should be used as the query in urls.py Any help would be appreciated. Thanks!

Upvotes: 0

Views: 382

Answers (2)

pkuphy
pkuphy

Reputation: 354

I think you can get this work by using redirect.

  1. Add a url for /search/ endpoint in your form:

    url(r'^search/$', views.search_redirect),
    
  2. In the views:

    def search_redirect(request):
        query = request.POST.get('query', '')
        return redirect('/search/{}/'.format(query))
    
  3. the form in your index.html should use method 'POST':

    <form action="/search/" method="POST">
      <input type="text" name="query" value="me"><br>
      <input type = "submit">
    </form>
    

When you submit the query string, search_redirect function get the query string and redirects the request to your /search/<query>/ function.

Hope this will help.

Upvotes: 2

Abijith Mg
Abijith Mg

Reputation: 2693

EDIT: Your current search url needs query value also to be passed. But in form action only /search/ is there. During the form submission query value will be passed in request.POST and you wont be able to pass the the query value directly in the url like this /search/sample_query

You need to add one more url:

url(r'^search/$', views.search, name='search'),

And in views:

def search(request, query_via_url=false):
    # if form submission is true
    if request.post:
        query_via_form = request.post.get('query', '')
        ...

    # if query value is passed directly via url
    if query_via_url:
        ....

Upvotes: 1

Related Questions