Django 将 URL 参数从模板传递到视图时出错:找不到 NoReverseMatch Reverse。尝试了 1 种模式

Django Error passing URL argument from Template to View: NoReverseMatch Reverse not found. 1 pattern(s) tried

我正在尝试通过配置 URL 像这样:

/details/12345

模板HTML:

    <div class="row">
    {% if article_list %}
    {% for article in article_list %}
    <div>
      <h2>{{ article.title }}</h2>
      <p>{{ article.body }}</p>
      <p><a class="btn btn-default" href="{% url 'details' article.id %}" role="button">View details &raquo;</a></p>
    </div><!--/.col-xs-6.col-lg-4-->
    {% endfor %}
    {% endif %}
  </div><!--/row-->

urls.py(已满):

    from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'news_readr.views.home', name='home'),
    url(r'^details/(?P<article_id>\d+)/$', 'news_readr.views.details', name='details'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py:

from django.shortcuts import render
from .models import Article

# Create your views here.
def home(request):
    title = "Home"
    article_list = Article.objects.all()
    for article in article_list:
        print(article.id)
    context = {
               "title": title,
               "article_list": article_list,
               }
    return render(request, "home.html", context)

def details(request, article_id = "1"):
    article = Article.objects.get(id=article_id)
    return render(request, "details.html", {'article': article})

我收到一条错误消息:

 NoReverseMatch at /

Reverse for 'details' with arguments '()' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['details/(?P<article_id>\d+)/$']

我在 Django 工作一周了,我认为我的 URL 命名组配置有问题。请帮忙! TIA!

更新:如果我删除 URL 配置并将其更改回:

url(r'^details/$', 'news_readr.views.details', name='details'),

错误变为:

Reverse for 'details' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['details/$']

因此,在这种情况下,它似乎正在获取传递给 1 的参数。所以这似乎是正则表达式的问题。我在 Pythex 上尝试了这个表达式,但即使在那里,该表达式似乎也没有匹配任何东西。

对于 url 模式

url(r'^details/(?P<article_id>\d+)/$', 'news_readr.views.details', name='details'),

标签的正确使用方法是

{% url 'details' article.id %}

这是因为 details url 模式有一个组 article_id,所以你必须将它传递给标签。

如果你有上面的url模式,并且{{ article.id}}在模板中显示正确,那么上面的模板标签应该不会给出错误Reverse for 'details' with arguments '()'。那说明你没有更新代码,或者你修改代码后没有重启服务器

如果将 url 模式更改为

url(r'^details/$', 'news_readr.views.details', name='details')

那么您需要从 url 标签中删除 article.id

{% url 'details' %}

我猜你的模式是错误的。(不是正则表达式专家)。 试试这个

url(r'^details/((?P<article_id>[0-9]+)/$', 'news_readr.views.details', name='details'),