首页 > 解决方案 > 如何在 Django 中通过 POST 方法进行搜索

问题描述

我正在尝试显示搜索结果页面。如果找到查询,它将被重定向到入口页面。否则,如果找到查询的子字符串,将显示搜索结果页面,其中条目显示为链接,如果单击该链接,将显示条目页面。这是我的代码如下,请帮助:

网址.py:

from django.urls import path
from . import views

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

视图.py:

from . import util
import markdown2
import random
from django.shortcuts import HttpResponse
from django.http import HttpResponseRedirect
from django.urls import reverse
from django import forms

def index(request):
    entries = util.list_entries()
    rand = random.choice(entries)
    return render(request, "encyclopedia/index.html", {
        "random": rand,
        "entries": entries
    })

def entry(request, title):
    entries = util.list_entries()
    rand = random.choice(entries)
    try: 
        mark_content = util.get_entry(title)
        output = markdown2.markdown(mark_content)
        return render(request, "encyclopedia/title.html", {
            "content": output,
            "random": rand,
            "title": title
        })

    except TypeError:
        return render(request, "encyclopedia/error.html", {
            "random": rand
        })

def search(request):
    # get search input from user
    search_entry = request.POST['q']
    # results = list()

    # get entries list
    entries = util.list_entries()

    # search list
    results = []
    
    # try to search if there is such entry in entries
    if request.method == "POST":
        if search_entry in entries:
            return HttpResponseRedirect(reverse("title", args=(search_entry,)))
        
        else: 
            for entry in entries: 
                if search_entry in entry: 
                    results.append(entry)
                    return render(request, "encyclopedia/search.html", {
                        "results": results
                    })

布局.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 action="{% url 'search' %}" method="post">
                    {% csrf_token %}
                    <input class="search" type="text" name="q" placeholder="Search Encyclopedia">
                </form>
                <div>
                    <a href="{% url 'index' %}">Home</a>
                </div>
                <div>
                    <a href="">Create New Page</a>
                </div>
                <div>
                    <a href="{% url 'entry' random %}">Random Page</a>
                </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 %}

    <h2>Search results:</h2>
    <ul>
        {% for result in results %}
            <li>
                <a href="{% url 'entry' result %}">{{ result }}</a>
            </li>
        {% empty %}
            <li>No result.</li>
        {% endfor %}
    </ul>  

{% endblock %}

Q1:我使用POST作为查询方法,因为我想将URL显示为/wiki/search搜索结果页面,但是使用GET作为方法,URL会像?q=&。我对这部分有点困惑,因为当我在维基百科中搜索 HTML 时,URL 会像:https://en.wikipedia.org/wiki/HTML,但是当我右键单击并检查页面时,方法是“得到”。

Q2:我应该在这里使用 TypeError 吗?如果用户输入的 URL 为 wiki/hello,并且没有 hello 的入口页面,则会显示错误页面,表示没有 hello 页面。

Q3:当我搜索时,它总是显示错误页面。为什么?我已经为入口函数提供了 args,但它似乎没有得到正确的参数。

标签: django

解决方案


我知道 Q3 的答案:创建 urls.py 中的 url 的顺序。

Django 会从上到下寻找路径,所以它在第二个入口函数处停止,并没有到达下面的搜索路径。我更改了订单,当我再搜索时它不再显示错误页面。虽然搜索仍然不起作用。需要帮助。


推荐阅读