Django NoReverseMatch URL模式

时间:2018-08-21 01:28:03

标签: python django url

我在此错误上受阻,无法解决。这是一个NoReverse Match错误。我最初的想法是,他们写我的网址格式的方式。我尝试了许多不同的url模式,但似乎没有用。我不熟悉何时使用path vs re_path。

错误:

django.urls.exceptions.NoReverseMatch: Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topic/(?P<entry_id>\\d+)/$']

文件urls.py:

urlpatterns = [
    # Home page
    path('', views.index, name='index'),

    # Show all Categories
    path('categories/', views.categories, name='categories'),

    # Show all topics associated with category
    re_path(r'^topics/(?P<category_id>\d+)/$', views.topics, name='topics'),

    # Show single topics
    re_path(r'^topic/(?P<entry_id>\d+)/$', views.topic, name='topic'),
]

views.py:

from django.shortcuts import render

from .models import Category, Entry, Topic
# Create your views here.


def index(request):
    """The home page for Learning Logs"""
    return render(request, 'blogging_logs/index.html')


def categories(request):
    """show all categories"""
    categories = Category.objects.all()
    context = {'categories': categories}
    return render(request, 'blogging_logs/categories.html', context)


def topics(request, category_id):
    """Show all topics for a single category"""
    category = Category.objects.get(id=category_id)  # get category that was requested
    topics = category.topic_set.all()  # get all topics associated with category that was requested
    context = {'category': category, 'topics': topics}
    return render(request, 'blogging_logs/category.html', context)


def topic(request, entry_id):
    """Show entry for single topic"""
    topic = Topic.objects.get(id=entry_id)
    entries = topic.entry_set.all()
    context = {'topic': topic, 'entries': entries}
    return render(request, 'blogging_logs/topic.html', context)

Categories.html

{% block content %}
  <p>Categories</p>
  <ul>
    {% for category in categories %}
    <li><a href="{% url 'blogging_logs:topics' category.id %}">{{ category }}</a></li>
    {% empty %}
      <li>No categories entered yet.</li>
      {% endfor %}
  </ul>
{% endblock content %}

Category.html

{% block content %}
  <h1>{{ Categories }}</h1>

  <p>Topics:</p>
  <ul>
      {% for topic in topics %}
        <li><a href="{% url 'blogging_logs:topic' entry.id %}">{{ topic }}</a></li>
        <p>{{topic.date_added|date:'M d, Y H:i' }}</p>
        {% empty %}
          <li>No categories entered yet.</li>
      {% endfor %}
  </ul>
{% endblock content %}

1 个答案:

答案 0 :(得分:1)

Category.html

{% block content %}
  <h1>{{ Categories }}</h1>

  <p>Topics:</p>
  <ul>
      {% for topic in topics %}
        <li><a href="{% url 'blogging_logs:topic' topic.id %}">{{ topic }}</a></li>
        <p>{{topic.date_added|date:'M d, Y H:i' }}</p>
        {% empty %}
          <li>No categories entered yet.</li>
      {% endfor %}
  </ul>
{% endblock content %}

它是topic.id而不是entry.id,在Category.html中没有名为entry的变量。