如何解决Django中的HttpResponseRedirect没有重定向到页面views.py文件
我的views.py如下:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django import forms
from . import util
import markdown2
def index(request):
return render(request,"encyclopedia/index.html",{
"entries": util.list_entries()
})
def entry(request,title):
if title not in util.list_entries():
return render(request,"encyclopedia/error.html",{
"error": "Page Not Found","query": title
})
else:
return render(request,"encyclopedia/entry.html",{
"entry": markdown2.markdown(util.get_entry(title)),"title": title
})
def search(request):
if request.POST["q"] in util.list_entries():
return HttpResponseRedirect(reverse("entry",args=(request.POST["q"],)))
else:
return render(request,"encyclopedia/error.html")
这是我的urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("",views.index,name="index"),path("<str:title>",views.entry,name="entry"),path("search",views.search,name="search")
]
接下来是我的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 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>
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>
如果搜索与查询匹配(如果它与我的输入匹配),那么我需要在这里将用户重定向到输入页面。我在views.py中的输入功能可以正常工作(如果标题匹配,则呈现entry.html),但是搜索功能未重定向到输入页面。在这种情况下正确的方法是什么?
解决方法
if request.POST["q"] in util.list_entries():
仅当搜索字符串与条目完全匹配时,此行才会匹配。
您可以循环浏览条目,并检查条目是否包含搜索字符串。例如:
for entry in util.list_entries():
if request.POST["q"] in entry:
return HttpResponseRedirect(reverse("entry",args=(entry,)))
,
也许您必须使用“重定向”
导入redirect
:
from django.shortcuts import redirect
可能有效。
,解决了。问题出在我应用程序的urls.py文件中。路径冲突。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。