我在/获得NoreverseMatch。

时间:2019-08-23 04:53:22

标签: python django

我正在尝试为我的项目改进模型和html文件,并且在Internet ive上找到解决方案时遇到了这个特殊错误。

我尝试导入渲染器和解析器,还尝试寻找关于stackoverflow的解决方案,但对我来说没有用。

这是urls.py

  from django.contrib import admin
  from django.urls import path
  from accounts import views as accounts_views
  from django.contrib.auth import views as auth_views
  from boards import  views

  urlpatterns = [

                  path('boards/<int:pk>/topics/<topic_pk>/', 
                        views.topic_posts, name='topic_posts'),
                  path('boards.<int:pk>/topics/<topic_pk>/reply/', 
                        views.reply_topic, name='reply_topic'),
                  ]

这是base.html中显示错误的行

    <button class="navbar-toggler" type="button" data-toggle="collapse" 
            data-target="#mainMenu" aria-controls="mainMenu" aria- 
                  expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

这是我的models.py文件

  from django.contrib.auth.models import User
  from django.db import models
  from django.utils.text import Truncator


  class Board(models.Model):
    name = models.CharField(max_length=30, unique=True)
    description = models.CharField(max_length=100)

    def __str__(self):
       return self.name

    def get_posts_count(self):
       return Post.objects.filter(topic__board=self).count()

    def get_last_post(self):
       return Post.objects.filter(topic__board=self).order_by('- 
            created_at').first()

这是html文件

 {% for board in boards %}
    <tr>
      <td>
        <a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a>
        <small class="text-muted d-block">{{ board.description }}</small>
      </td>
      <td class="align-middle">
        {{ board.get_posts_count }}
      </td>
      <td class="align-middle">
        {{ board.topics.count }}
      </td>
      <td class="align-middle">
        {% with post=board.get_last_post %}
          <small>
            <a href="{% url 'topic_posts' board.pk post.topic.pk %}">
              By {{ post.created_by.username }} at {{ post.created_at }}
            </a>
          </small>
        {% endwith %}
      </td>
    </tr>
  {% endfor %}

我收到此错误

 "Reverse for 'topic_posts' with arguments 
  '(3, '')' not found. 1 pattern(s) tried: ['boards/(?P<pk>[0- 
  9]+)/topics/(?P<topic_pk>[^/]+)/$']"

1 个答案:

答案 0 :(得分:0)

很明显,您的topic_pk是一个空字符串,从错误消息中可以看出:

[...] with arguments  '(2, '')' [...]