我的 Django 教程的 NoReverseMatch 问题

NoReverseMatch problem with my tutorial for Django

正在阅读 Python 速成课程中的 Django 教程,但我正面临困境。我得到的错误是 '为 'topic' 反向,参数 '('',)' 未找到。尝试了 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 来自 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) 

topic.html {% 扩展 '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 文档,但我对自己的理解还不足以解决这个问题。如果我需要添加更多代码来提供帮助,请告诉我。非常感谢所有帮助。

编辑: Topics.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%}

在您的模板中,您试图访问 topic,但在 views.py 中,您没有将 topic 变量传递给 context。在您的 context 变量中传递 topic

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, 'topic': topic}
    return render(request, 'learning_logs/topic.html', context) 

问题出在topics.html。这是显示每个主题的循环:

    {%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%}

变量topic_id未定义。那应该是 topic.id,它访问 topicid 属性。