【问题标题】:Djano first project search issueDjango第一个项目搜索问题
【发布时间】:2020-07-12 21:35:18
【问题描述】:

这是我坚持的项目的一部分:

搜索:允许用户在侧边栏中的搜索框中键入查询以搜索百科全书条目。 如果查询与百科全书条目的名称匹配,则应将用户重定向到该条目的页面。 如果查询与百科全书条目的名称不匹配,则应将用户转至搜索结果页面,该页面显示将查询作为子字符串的所有百科全书条目的列表。例如,如果搜索查询是 Py,那么 Python 应该出现在搜索结果中。 单击搜索结果页面上的任何条目名称应将用户带到该条目的页面。

我的代码:

urls.py

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>", views.wiki, name="wiki"),
    path("search", views.search, name="search"),
]

util.py

import re

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage


def list_entries():
    """
    Returns a list of all names of encyclopedia entries.
    """
    _, filenames = default_storage.listdir("entries")
    return list(sorted(re.sub(r"\.md$", "", filename)
                for filename in filenames if filename.endswith(".md")))


def save_entry(title, content):
    """
    Saves an encyclopedia entry, given its title and Markdown
    content. If an existing entry with the same title already exists,
    it is replaced.
    """
    filename = f"entries/{title}.md"
    if default_storage.exists(filename):
        default_storage.delete(filename)
    default_storage.save(filename, ContentFile(content))


def get_entry(title):
    """
    Retrieves an encyclopedia entry by its title. If no such
    entry exists, the function returns None.
    """
    try:
        f = default_storage.open(f"entries/{title}.md")
        return f.read().decode("utf-8")
    except FileNotFoundError:
        return None

views.py

from django.shortcuts import render

from . import util


def index(request):
    return render(request, "encyclopedia/index.html", {
        "entries": util.list_entries()
    })
    
def wiki(request, title):
    return render(request, "encyclopedia/wiki.html", {
        "entries": util.get_entry(title)
    })
    
def search(request): 
    entries = util.list_entries()
    find_entries = list()

    search_box = request.POST.get("q").capitalize()

    if search_box in entries:
        return HttpResponseRedirect(f"wiki/{search_box}")
        
    for entry in entries:
        if search_box in entry:
           find_entries.append(entry)
        else:
            print(f'{find_entries}')
        
    if find_entries:
        return render(request, "encyclopedia/search.html", {
          "search_result": find_entries,
          "search": search_box
    })
    

layout.html

{% load static %}

<!DOCTYPE html>

<html lang="en">
    <head>
        <title>{% block title %}{% endblock %}</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
    </head>
    <body>
        <div class="row">
            <div class="sidebar col-lg-2 col-md-3">
                <h2>Wiki</h2>
               <form method="get" action="{% url 'search' %}">
                {% csrf_token %}
                <input type="text" name="q" placeholder="Search Encyclopedia">
                </form>
                <div>
                    <a href="{% url 'index' %}">Home</a>
                </div>
                <div>
                    Create New Page
                </div>
                <div>
                    Random Page
                </div>
                {% block nav %}
                {% endblock %}
            </div>
            <div class="main col-lg-10 col-md-9">
                {% block body %}
                {% endblock %}
            </div>
        </div>

    </body>
</html>

搜索.html

{% extends "encyclopedia/layout.html" %}

{% block title %}
    search results
{% endblock %}

{% block body %}
    {% for result in search_result %}
        <li><a href=wiki/{{ result }}>{{ result }}</a></li>
    {% endfor %}
    <h1>{{ no_result }}</h1>
{% endblock %}

我收到以下错误:/search 处的 AttributeError “NoneType”对象没有“大写”属性

请帮忙

【问题讨论】:

  • 将此行search_box = request.POST.get("q").capitalize() 替换为search_box = request.POST.get("q", "").capitalize()

标签: python django


【解决方案1】:

出现问题是因为您的 layout.html 模板中的表单使用了get 方法,但您的views.py 中的search 函数正在检查request.POST

你需要更新views.py中的search函数:

search_box = request.POST.get("q").capitalize()  # remove this
search_box = request.GET.get("q").capitalize()  # add this

您还可以删除 layout.html 模板中的 {% csrf_token %},因为它是 not required for GET requests

【讨论】:

  • 好的,现在我没有收到错误消息。但是,不是我的匹配搜索转到我列出的项目的条目页面。它将进入我的搜索页面。例如,如果我将 CSS 放在搜索中,它会转到列出我所有条目的搜索页面。而不是我创建的 wiki.html 页面
  • 好的。 if search_box in entries: 似乎没有返回 True。您是否检查过util.list_entries() 的输出是否符合您的预期?您还尝试过哪些其他问题来诊断问题?
  • 是的,它正确地返回列表,并将它们 html 到适当的条目......是的,它肯定不会像真的那样工作。我认为它在这部分“if search_box in entry: find_entries.append(entry)”我认为我需要将其替换为运行 wiki 功能。我只是不确定如何
  • 我觉得我需要将 wiki 导入搜索功能,因为我试图将其添加到列表中,而这不是我想做的
  • 我尝试这样做:对于条目中的条目:如果条目中的 search_box:返回 wiki (request, {"entries": util.get_entry(title)}) else: print(f'{find_entries }') 但它返回为 NameError at /search name 'title' is not defined
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多