Django在使用For循环和url方法时为什么会引发NoReverseMatch错误?

huangapple go评论147阅读模式
英文:

Why does Django raise a NoReverseMatch error when using the 'entry' iterator in a For loop and url method?

问题

以下是您提供的代码部分的中文翻译:

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

{% block title %}
    百科全书
{% endblock %}

{% block body %}
    <h1>所有页面</h1>

    <ul>
        {% for entry in entries %}
            <li><a href="{% url 'entry' title=entry %}">{{ entry }}</a></li>
            {% comment %} <p> {{ entry }} </p> {% endcomment %}
        {% endfor %}
    </ul>
    {% comment %} <a href="/wiki/{{ entry }}"> <li>{{ entry }}</li> </a> {% endcomment %}

{% endblock %}
from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>", views.entry, name="entry"),
    path("search/", views.search, name="search"),
    path("new/", views.new_page, name="new_page"),
    path("edit/", views.edit, name="edit"),
    path("save_edit/", views.save_edit, name="save_edit"),
    path("rand/", views.rand, name="rand")
]
from django.shortcuts import render
import markdown
from . import util
import random

def convert_md_to_html(title):
    content = util.get_entry(title)
    markdowner = markdown.Markdown()
    if content == None:
        return None
    else:
        return markdowner.convert(content)

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

def entry(request, title):
    html_content = convert_md_to_html(title)
    if html_content == None:
        return render(request, "encyclopedia/error.html",{
            "message": "该条目不存在"
        })
    else:
        return render(request, "encyclopedia/entry.html",{
            "title": title,
            "content": html_content
        })

def search(request):
    if request.method == "POST":
        entry_search = request.POST['q']
        html_content = convert_md_to_html(entry_search)
        if html_content is not None:
            return render(request, "encyclopedia/entry.html",{
                "title": entry_search,
                "content": html_content
        })

        else:
            allEntries = util.list_entries()
            recommendation = []
            for entry in allEntries:
                if entry_search.lower() in entry.lower():
                    recommendation.append(entry)
            return render(request, "encyclopedia/search.html", {
                "recommendation": recommendation
            })

def new_page(request):
    if request.method == "GET":
        return render(request, "encyclopedia/new.html")
    else:
        title = request.POST['title']
        content = request.POST['content']
        titleExist = util.get_entry(title)
        if titleExist is not None:
            return render(request, "encyclopedia/error.html", {
                "message": "该条目已存在"
            })
        else:
            util.save_entry(title, content)
            html_content = convert_md_to_html(title)
            return render(request, "encyclopedia/entry.html", {
                "title": title,
                "content": html_content
            })

def edit(request):
    if request.method == 'POST':
        title = request.POST['entry_title']
        content = util.get_entry(title)
        return render(request, "encyclopedia/edit.html",{
            "title": title,
            "content": content
        })

def save_edit(request):
    if request.method == "POST":
        title = request.POST['title']
        content = request.POST['content']
        util.save_entry(title, content)
        html_content = convert_md_to_html(title)
        return render(request, "encyclopedia/entry.html",{
            "title": title,
            "content": html_content
        })

def rand(request):
    allEntries = util.list_entries()
    rand_entry = random.choice(allEntries)
    html_content = convert_md_to_html(rand_entry)
    return render(request, "encyclopedia/entry.html",{
        "title" : rand_entry,
        "content" : html_content
    })

请注意,代码中的中文翻译只是将英文内容翻译成中文,但并没有更改代码逻辑。如果您需要进一步的帮助或解释,请随时提出。

英文:

NoReverseMatch at /
Reverse for 'entry' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried:['wiki/(?P<title>[^/]+)\Z'] Line 12.


{% extends &quot;encyclopedia/layout.html&quot; %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
&lt;h1&gt;All Pages&lt;/h1&gt;
&lt;ul&gt;
{% for entry in entries %}
&lt;li&gt;&lt;a href=&quot;{% url &#39;entry&#39;  title=entry %}&quot;&gt;{{ entry }}&lt;/a&gt;&lt;/li&gt; 
{% comment %} &lt;p&gt; {{ entry }} &lt;/p&gt; {% endcomment %}
{% endfor %}
&lt;/ul&gt; 
{% comment %} &lt;a href &quot;/wiki/{{ entry }}&quot;&gt; &lt;li&gt;{{ entry }}&lt;/li&gt; &lt;/a&gt; {% endcomment %}
{% endblock %}

I am trying to print a list of entries with their links, but Django complains about the iterator 'entry' in the For cycle, it can actually print the elements of the list, but when using the url django method, it won't render the page 'cause that error.

urls.py


from django.urls import path
from . import views
urlpatterns = [
path(&quot;&quot;, views.index, name=&quot;index&quot;),
path(&quot;wiki/&lt;str:title&gt;&quot;, views.entry, name=&quot;entry&quot;),
path(&quot;search/&quot;, views.search, name=&quot;search&quot;),
path(&quot;new/&quot;, views.new_page, name=&quot;new_page&quot;),
path( &quot;edit/&quot;, views.edit, name=&quot;edit&quot;),
path( &quot;save_edit/&quot;, views.save_edit, name=&quot;save_edit&quot;),
path( &quot;rand/&quot;, views.rand, name= &quot;rand&quot;)
]

views.py


from django.shortcuts import render
import markdown
from . import util
import random
def convert_md_to_html(title):
content = util.get_entry(title)
markdowner = markdown.Markdown()
if content == None:
return None
else:
return markdowner.convert(content)
def index(request):
return render(request, &quot;encyclopedia/index.html&quot;, {
&quot;entries&quot;: util.list_entries()
})
def entry(request, title):
html_content = convert_md_to_html(title)
if html_content == None:
return render(request, &quot;encyclopedia/error.html&quot;,{
&quot;message&quot;: &quot;This entry does not exist&quot;
})
else:
return render(request, &quot;encyclopedia/entry.html&quot;,{
&quot;title&quot;: title,
&quot;content&quot;: html_content
})
def search(request):
if request.method == &quot;POST&quot;:
entry_search = request.POST[&#39;q&#39;]
html_content = convert_md_to_html(entry_search)
if html_content is not None:
return render(request, &quot;encyclopedia/entry.html&quot;,{
&quot;title&quot;: entry_search,
&quot;content&quot;:html_content
})
else:
allEntries = util.list_entries()
recommendation = []
for entry in allEntries:
if entry_search.lower() in entry.lower():
recommendation.append(entry)
return render(request, &quot;encyclopedia/search.html&quot;, {
&quot;recommendation&quot;: recommendation
})
def new_page(request):
if request.method == &quot;GET&quot;:
return render(request, &quot;encyclopedia/new.html&quot;)
else:
title = request.POST[&#39;title&#39;]
content = request.POST[&#39;content&#39;]
titleExist = util.get_entry(title)
if titleExist is not None:
return render(request, &quot;encyclopedia/error.html&quot;, {
&quot;message&quot;: &quot;Entry page already exist&quot;
})
else:
util.save_entry(title, content)
html_content = convert_md_to_html(title)
return render(request, &quot;encyclopedia/entry.html&quot;, {
&quot;title&quot;: title,
&quot;content&quot;: html_content
})
def edit(request):
if request.method == &#39;POST&#39;:
title = request.POST[&#39;entry_title&#39;]
content = util.get_entry(title)
return render(request, &quot;encyclopedia/edit.html&quot;,{
&quot;title&quot;: title,
&quot;content&quot;: content
})
def save_edit(request):
if request.method == &quot;POST&quot;:
title = request.POST[&#39;title&#39;]
content = request.POST[&#39;content&#39;]
util.save_entry(title, content)
html_content = convert_md_to_html(title)
return render(request, &quot;encyclopedia/entry.html&quot;,{
&quot;title&quot;: title,
&quot;content&quot;: html_content
})
def rand(request):
allEntries = util.list_entries()
rand_entry = random.choice(allEntries)
html_content = convert_md_to_html(rand_entry)
return render(request, &quot;encyclopedia/entry.html&quot;,{
&quot;title&quot; : rand_entry,
&quot;content&quot; : html_content
})

答案1

得分: 1

根据错误消息所说,其中一个条目是空字符串''。空字符串与任何URL参数都不匹配。

查看您的视图函数,似乎故意允许空字符串。如果是这样,您可以尝试使用re_path

from django.urls import re_path

urlpatterns = [
    # regular paths
    re_path(r'^entry/(?P<title>[\w]*)$', views.entry, name='entry')
]

请注意,\w将匹配字母数字字符以及下划线。如果您的条目包含其他字符,例如破折号-,则您需要更改这个正则表达式。

英文:

As the error message says, one of the entries is an empty string &#39;&#39;. An empty string does not match with any url parameter.

Looking into your view function, en empty string seems to be intentionally allowed. If so, you can try re_path

from django.urls import re_path
urlpatterns = [
# regular paths
re_path(r&#39;^entry/(?P&lt;title&gt;[\w]*)$&#39;, views.entry, name=&#39;entry&#39;)
]

Please note \w will match alphanumeric characters as well as underscore. If your entry contains other characters, e.g. dash -, you will have to change this re expression.

huangapple
  • 本文由 发表于 2023年6月5日 05:00:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定