Sunday, July 27, 2014

Django Search via Form Redirect to URL

I already have a valid search function mapped in my Django project, you type in a url '/project/search//' and it responds the corresponding search results on a page. I want to have a search box in my nav-bar that was created in my base.html and have users type in a query and it will redirect them to the search url. When I type into the search bar and click submit, however, the I am just directed to '/project/search/' with no relation to the query. How do I connect the form to redirect to the URL, properly??

Thanks in advance.

Here is my view definition and form class:

class SearchForm(forms.Form):      search_string = forms.CharField(max_length=100)  def search(request, search_query):      if request.method == 'GET':          form = SearchForm()          context = RequestContext(request)          search_string = search_query.replace('_',' ')          search_terms = search_query.split('_')          search_results = Article.objects.all()          for term in search_terms:              search_results = search_results.filter(article__icontains=term)            context_dict = {              'search_string':search_string,              'search_results':search_results,              'form':form,          }          if request.method == 'POST':          form = SearchForm(request.POST)          if form.is_valid():              search_string = form.data['search_string']              search_query = search_string.replace(' ','_')              ###return HttpResponseRedirect(reverse('search', args=(search_query,)))              search_url = '/beacon/search/' + search_query + '/'              return HttpResponseRedirect(search_url)      else:          return render_to_response('search.html', context_dict, context)

My base form html is (yes it is from bootstrap):

<form action='/beacon/search/' class="navbar-form navbar-right" role="search" method='POST'>      <div class="form-group">          {% csrf_token %}          <input type="text" class="form-control" placeholder="Search Article Text">      </div>      <button type="submit" class="btn btn-default">Submit</button>  </form>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/952d7d70-4f65-4283-bcd0-45e4385ae672%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment