Chris
Chris

Reputation: 62

Django URL from HTML search form

In my template I am using an input with the type "search". When an action is performed it returns the page "/search_results.html".

The issue I'm having is that it appends /?search=yoursearch to the end of the URL.

My URL pattern is

url(r'^search_results/(?P<search>\w+)/$, views.SearchView, name='search')

So right now if I type localhost:8000/search_results/apple, it will return results that contain the word apple. But if I use the search bar to search apple it returns localhost:8000/search_results/?search=apple, which is not a valid URL. I tried using

(?P<search>.*)

instead, but it said too many redirects.

Does anyone know how to use the value from a search result in Django? Or is there a way to arrange my URL so that I can parse the bit after the equals sign? Thanks

Upvotes: 0

Views: 1918

Answers (3)

tushortz
tushortz

Reputation: 5095

In views.py

# no need to edit this
def normalize_query(query_string,
                findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
                normspace=re.compile(r'\s{2,}').sub):
    ''' Splits the query string in invidual keywords, getting rid of 
        unecessary spaces and grouping quoted words together.
    '''
    return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]


# no need to edit this
def get_query(query_string, search_fields):
    ''' Returns a query, that is a combination of Q objects. That combination aims to search keywords within a model by testing the given search fields.'''

    query = None # Query to search for every search term
    terms = normalize_query(query_string)

    for term in terms:
        or_query = None # Query to search for a given term in each field
        for field_name in search_fields:
            q = Q(**{"%s__icontains" % field_name: term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query

the search view to edit

def search(request):
    books = Mymodel.objects.all()
    query_string = ''
    found_entries = None
    source = ""

    # the 'search' in this request.GET is what appears in the url like
    #localhost:8000/?search=apple. 
    if ('search' in request.GET) and request.GET['search'].strip():
        query_string = request.GET['q']
        entry_query = get_query(query_string, [list, of, model, field, to, search])
    found_entries = Mymodel.objects.filter(entry_query)

    context = {
        'query_string': query_string,
        'found_entries': found_entries,
    }

    return render(request, 'pathto/search.html', context)

Now in urls.py all you need do is add this in the url pattern

url(
    regex=r'^search/$',
    view = search,
    name = 'search'
  ),

Upvotes: 0

Calder White
Calder White

Reputation: 1326

Not totally sure what your goal is, but I do know when matching urls django ignores the query string (which can be accessed in the request object via request.META["QUERY_STRING"]. Here's a little example handler for searches.
urls.py

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^/search_results',views.search_handler)

views.py

def search_handler(request):
    query = {}
    for i in request.META["QUERY_STRING"].split("&"):
        query[i.split("=")[0]] = i.split("=")[1]
    search = query["search"]
    # your code here

Upvotes: 1

Hannan
Hannan

Reputation: 55

In your html form, are you using method get or post?

<form method="post">
</form>

Upvotes: 0

Related Questions