NoReverseMatch at / list

北城以北 提交于 2021-01-28 03:59:06

问题


I tried get dynamic link

Error:

NoReverseMatch at /

Reverse for 'new_single' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['single/']

Code: view:

{% for new in news %}

    {{ new.id }}
     <h2><a href="{% url 'new_single' pk=new.id %}">{{ new.title }}</a></h2>
{% endfor %}

urls:

urlpatterns = [
    url(r'^$', views.news_list, name='news_list'),
    url(r'single/<int:pk>', views.new_single, name="new_single"),
]

views:

def new_single(request,pk):
    new=get_object_or_404(News,id=pk)
    return render(request,"news/news_single.html",{"new":new})

回答1:


You are mixing two syntax variants to specify patterns. Since django-2.0 there are two ways to specify URL patterns: with path(..) [Django-doc], and with re_path(..) [Django-doc] for regular expressions-like patterns (an alias is url(..) [Django-doc]).

You however mix the two. You can use the two concurrently, but you need to specify per urlpatterns entry the correct one:

#  app/urls.py

from django.urls import path, re

urlpatterns = [
    url(r'^$', views.news_list, name='news_list'),
    path('single/<int:pk>/', views.new_single, name="new_single"),
]


来源:https://stackoverflow.com/questions/52136598/noreversematch-at-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!