1π
β
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
π€Calder White
0π
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'
),
π€tushortz
- Postgresql error: undefined symbol: GEOSClipByRect in django
- How to create nested form in django?
- Django: What is the basic difference beween User and Anonymous user?
- Django searching function issue
- <h1> styling not working but others will
Source:stackexchange.com