问题描述
你好,我试图将编辑页面添加到我的django url模式中,并且当我单击页面上的链接之一时,该页面给我一个错误,系统崩溃了,并且系统显示了一个无反向匹配错误系统。如果我确实将编辑路径与输入路径交换了,那么它确实可以工作,但是那不是我想要的方式。我希望首先为用户显示条目页面,然后单击编辑按钮以编辑页面。下面是我的观点和一些html页面。
django的新手,查看了文档,但没有找到任何东西。谢谢你的帮助
以下也是错误:
错误-参数'('## Django \ r \ n \ r \ n颠倒为'edit'Django是使用Python编写的Web框架,允许设计生成{{3}的Web应用程序}动态。\ r \ n',)'未找到。尝试了1个模式:['(?P [^ /] +)$']
urls.py:
from django.urls import path
from . import views
app_name = "enc"
urlpatterns = [
path("",views.index,name="index"),path("new_page",views.new_page,name="check_page"),path("",views.get_search,name="search"),path("<str:title>",views.entry,name="page"),views.edit,name ="edit"),]
views.py
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from . import util
entries = {}
def index(request):
return render(request,"encyclopedia/index.html",{
"entries": util.list_entries()
})
def entry(request,title):
if util.get_entry(title):
return render(request,"encyclopedia/entry.html",{
"title": util.get_entry(title),"name":title
})
else:
return render(request,"encyclopedia/error.html")
def get_search(request):
if request.method == 'GET':
form = util.search_form(request.GET['q'])
if form.is_valid():
search = form.cleaned_data["search"]
return render(request,{
"search":util.get_entry(search)
})
def new_page (request):
if request.method == 'POST':
form = util.new_entry(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
details = form.cleaned_data['details']
if title in entries:
return render (request,"encyclopedia/error.html")
else:
util.save_entry(title,details)
entries[title] = details
return HttpResponseRedirect(f'{title}')
return render(request,"encyclopedia/new_page.html",{
"form": util.new_entry()
})
def edit (request,title):
entry = util.get_entry(title)
if entry == None:
return render(request,"encyclopedia/error.html")
else:
form = util.edit(initial={'title':title,'details':entry})
return render (request,"encyclopedia/edit.html",{
"form": form,'title': title,'details':util.get_entry(title),} )
用于编辑的HTML
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<form action="{% url 'enc:edit' title %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{% endblock %}
html条目
{% block title %}
{{name}}
{% endblock %}
{% block body %}
<p>{{title}}</p>
<a href="{% url 'enc:index' %}">Go back to main page</a>
<a href="{% url 'enc:edit' title %}">Click here to edit the page</a>
{% endblock %}
解决方法
如果两个视图的路径相同,Django将引发错误。 试试这个解决问题。
defaultdict
请谨慎使用/正斜杠