在 HTML 表单中调用视图作为操作属性的值,从而导致 NoReverseMatch 错误



我正在使用django创建一个web应用程序,现在我想添加一个修改条目的视图(我的web应用程序是一个百科全书,所以该视图允许我们编辑页面(。

点击以下html页面的链接,我们可以访问编辑页面:

{% extends "encyclopedia/layout.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block body %}
{{ html | safe }}
{% if exists %}
<br><br><br><br>
<a href="{{ address }}">Edit encyclopedia</a>
{% endif %}
{% endblock %}

所以django会通过这个url

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

然后,这个url应该会让我们看到这样的视图:

def edit(request, title):
if request.method == "POST":
form = NewForm(request.POST)
if form.is_valid():
with open(f"entries/{title}.md", "w") as file:
file.write(form.cleaned_data["content"])
return redirect(reverse("encyclopedia:display"))
else:
return render(request, "encyclopedia/edit.html",{
'form' : NewForm(),
'message' : """<div class="alert alert-danger" role="alert">
Your entries are empty.
</div>"""
})
markup = util.get_entry(title)[0]
print(request.)
return render(request, "encyclopedia/edit.html",{
'form'  : NewForm(),
'title' : title,
'markup': markup,
})

这是我的html文件:

{% extends "encyclopedia/layout.html" %}
{% block title %}
Edit
{% endblock %}
{% block body %}
<h1>New Encyclopedia</h1>
<p>Our websites' encyclopedias are written in a langage names Markdow<br>
You may have additionnal informations about this language <a href="https://docs.github.com/en/free-pro-team@latest/github/writing-on-github/basic-writing-and-formatting-syntax">here</a>.</p>
<form action="{% url 'encyclopedia:edit' %}" method="POST" style="display: block; text-align: center; padding: 20px;">
{% csrf_token %}
<p style="margin: 15px;">{{ title }}</p>
<textarea rows='10' placeholder="Encyclopedia's content" name="content" style="width: 90%; margin: 15px;">{{ markup }}</textarea>
<input type="submit" value="Edit" style="width:15%">
</form>
{% endblock %}

但我的问题是,当我运行我的应用程序并进入编辑页面时,我会得到一个NoReverseMatch错误,就像下面这样:

NoReverseMatch at/wiki/Django/edit未找到任何参数的"edit"的反转。已尝试1个图案:['wiki/(?P[^/]+(/edit$']

我认为这个问题与我在表单中调用编辑视图时没有给出标题参数有关,但我不知道如何做到这一点。

如果有人能帮助我,那将是令人惊讶的,我做了很多研究,但真的不知道如何解决这个问题。。。

我终于找到了错误的根源,这可能会对谁有所帮助,我放弃了添加"title"变量(这对我的视图来说是强制性的(,就像这样:

else:
return render(request, "encyclopedia/edit.html",{
'form'   : NewForm(),
'message': """<div class="alert alert-danger" role="alert">
Your entries are empty.
</div>""",
'title'  : title,
})

is_valid()方法并不真正对应于我想要如何处理数据,我用以下函数替换了它:

undecodables = ["è", "à", "é"]
def own_validation(string):
try:
valid = False
for i in string:
if i.isalnum : valid = True
assert i not in undecodables 
except AssertionError:
return False
else:
return valid

我不知道所有不可编码的字符是什么,所以这个列表将来会完成的。

感谢@iklinac的帮助!

最新更新