Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django-修改简单搜索结果的外观_Python_Django_Search - Fatal编程技术网

Python Django-修改简单搜索结果的外观

Python Django-修改简单搜索结果的外观,python,django,search,Python,Django,Search,我正在使用django迈出第一步,目前我正在尝试使用以下工具为我的网站应用简单的搜索解决方案: 这是代码的样子: search.py import re from django.db.models import Q def normalize_query(query_string, findterms=re.compile(r'"([^"]+)"|(\S+)').findall, normspace=re.compile(r'\

我正在使用django迈出第一步,目前我正在尝试使用以下工具为我的网站应用简单的搜索解决方案:

这是代码的样子:

search.py

import re

from django.db.models import Q

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.
    Example:

    >>> normalize_query('  some random  words "with   quotes  " and   spaces')
    ['some', 'random', 'words', 'with quotes', 'and', 'spaces']

'''
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] 

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
views.py

from news.models import *
from news.search import *
from django.shortcuts import render_to_response
from django.template import RequestContext

def search(request):
query_string = ''
found_entries = None
search_fields=('text','title',)

if ('q' in request.GET) and request.GET['q'].strip():

    query_string = request.GET['q']

    entry_query = get_query(query_string, search_fields)

    found_entries = News.objects.filter(entry_query).order_by('-id')

return render_to_response('search/search.html',
                      { 'query_string': query_string, 'found_entries': found_entries },
                      context_instance=RequestContext(request))
models.py

STATUS_CHOICES = (
              ('d', 'Draft'),
              ('p', 'Published'),
              ('w', 'Withdrawn'),
)

class News(models.Model):


category = models.ManyToManyField(Category, verbose_name='Kategorie')
title = models.CharField(max_length=255, verbose_name='Tytuł')
slug = models.SlugField(max_length=255, unique=True, verbose_name='Odnośnik')
text = models.TextField(verbose_name='Treść')
date = models.DateTimeField(verbose_name='Data dodania')
author = models.ForeignKey(User, verbose_name='Autor')
status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='d')


class Meta:
    verbose_name = "Wiadomość"
    verbose_name_plural = "Wiadomość"


def __str__(self):
    return self.title
def __unicode__(self):
    return self.title
def get_absolute_url(self):
    return '/news/' + self.slug + '/'
search.html

{% if found_entries %}
                <p>You searched for "{{ query_string }}".</p>            
                    <ul>
                    {% for i in found_entries %}
                        <li><a href="{{ q.get_absolute_url }}">{{found_entries }}</a></li>
                    {% endfor %}
                    </ul>
            {% endif %}
            {% if query_string and not found_entries %}
                <p>No results found.</p>
            {% else %}
                <p>Type a search query into the box above, and press "Submit" to search.</p>
            {% endif %}
{%if-find_-entries%}
您搜索了“{query\u string}}”。

    {在找到的_项中找到了%i}
  • {%endfor%}
{%endif%} {%if查询\u字符串且未找到\u条目%} 没有发现任何结果

{%else%} 在上面的框中键入搜索查询,然后按“提交”进行搜索

{%endif%}
我想做的是获得搜索结果的正确视图(通过新闻模型搜索,这应该会返回标题+两行文字?)这就是atm的外观:(我还不允许发布图像)


我花了至少几个小时才找到一个合适的解决方案,如何修改views.py和search.html以获得合适的视图结果,您能帮我一点忙吗?

这就是您的问题所在

                {% for i in found_entries %}
                    <li><a href="{{ i.get_absolute_url }}">{{i}}</a></li>
                {% endfor %}
{%fori-find_-entries%}
  • {%endfor%}
    当您仅显示
    {{i}}
    时,将使用模型的
    \uuuuuunicode\uuuuuu
    方法


    如果你想显示更多,你可以使用
    {{i.category}
    {{i.title}}
    等等。

    哦,伙计。。。我简直不敢相信,非常感谢#我甚至不能投票给你:(