【发布时间】:2021-02-14 03:06:01
【问题描述】:
通过Python Crash Course 中的 Django 教程,我正面临着一堵墙。我得到的错误是
'reverse for 'topic' with arguments '('',)' not found.尝试了 1 种模式:['topics/(?P<topic_id>\\d+)/$']'。
这是我的 urls.py
from django.conf.urls import URL
from . import views
urlpatterns = [
# the actual url patter is a call to the url () function, which takes three arguments
# Home page
url(r'^$', views.index, name='index'),
#Show all topics
url(r'^topics/$', views.topics, name='topics'),
# Detail page for a single topic
url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'),
]
app_name= 'learning_logs'
views.py from django.shortcuts 导入渲染
from .models import Topic
def index(request):
"""The home page for Learning Log"""
return render(request, 'learning_logs/index.html')
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics' : topics}
return render(request, 'learning_logs/topics.html', context)
def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)
主题.html {%extends 'learning_logs/base.html' %}
{%block content%}
<p>Topic: {{topic}}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{entry.date_added|date:'M d, Y H:i'}}</p>
<p>{{entry.text| linebreaks}}</p>
</li>
{% empty %}
<li>
There are no entries for this topic yet.
</li>
{% endfor %}
</ul>
{%endblock content%}
我已经阅读了一些Django 文档,但我的理解不足以自己解决这个问题。如果我需要添加更多代码来提供帮助,请告诉我。非常感谢所有帮助。
编辑: 主题.html
{%extends 'learning_logs/base.html'%}
{% block content%}
<p>Topics</p>
<ul>
{%for topic in topics%}
<li>
<a href="{% url 'learning_logs:topic' topic_id%}">{{topic}}</a>
</li>
{%empty%}
<li>No topics have been added yet</li>
{%endfor%}
</ul>
{% endblock content%}
【问题讨论】:
-
我是PCC的作者。您正在使用本书第一版的相当过时的版本。第一版的后续版本使用
path()结构作为url,而不是旧的url()结构。如果您对这个问题进行了分类,您可能会遇到其他问题,因为自从您的副本打印后 Django 发生了多少变化。 This 是我见过的解决NoReverseMatch错误的最佳 SO 帖子。至于这个具体问题,可能是topics.html文件有错误。 -
'Reverse for 'topic' with arguments '('',)' not found.这使得主题的 id 看起来没有通过 url 传递。你能发布你的topics.html文件吗? -
我知道你可能一直都在听,但你的书很棒。周围都很棒,感谢您花时间提供帮助。我查看了帖子,你标记了我想我知道我哪里出错了。并按要求发布了 Topics.html。
标签: python django reverse django-urls