Django URL来自HTML搜索表格



在我的模板中,我正在使用带有"搜索"类型的输入。执行操作后,它将返回页面"/search_results.html"。

我遇到的问题是它附加/?search = yours搜索到URL的末尾。

我的URL模式是

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

现在,如果我键入Localhost:8000/search_results/Apple,它将返回包含Apple一词的结果。但是,如果我使用搜索栏来搜索Apple,它将返回LocalHost:8000/search_results/?search = apple,这不是有效的URL。我尝试使用

(?P<search>.*)

相反,它说了太多的重定向。

有人知道如何从Django中的搜索结果中使用该值吗?还是有一种方法来排列我的URL,以便在符号符号之后解析位?谢谢

不完全确定您的目标是什么,但是我知道在匹配urls django 忽略时,查询字符串(可以通过request.META["QUERY_STRING"]在请求对象中访问。这是一个搜索的小示例处理程序。
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

在您的html表单中,您是使用方法get还是发布?

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

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

搜索视图要编辑

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)

现在在urls.py中,您需要做的就是将其添加到URL模式

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

最新更新