Python Django - 使用 {% url "music:fav" %} 时出现错误“Reverse for 'detail' with no arguments not found. 1 模式尝试:”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47944443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django - getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
提问by Vishal Ghosh
I am learning django framework from last 4 days. Today I was trying to retrieve a URL in HTML template by using
我从过去 4 天开始学习 django 框架。今天我试图通过使用检索 HTML 模板中的 URL
{% url "music:fav" %}
{% url "music:fav" %}
where I set the namespace in music/urls.py as
我将 music/urls.py 中的命名空间设置为
app_name= "music"
app_name=“音乐”
and also I have a function named fav(). Here is the codes:
我还有一个名为 fav() 的函数。这是代码:
music/urls.py
音乐/网址.py
from django.urls import path
from . import views
app_name = 'music'
urlpatterns = [
path("", views.index, name="index"),
path("<album_id>/", views.detail, name="detail"),
path("<album_id>/fav/", views.fav, name="fav"),
]
music/views.py
音乐/views.py
def fav(request):
song = Song.objects.get(id=1)
song.is_favorite = True
return render(request, "detail.html")
in detail.html I used
我使用的 detail.html
{% url 'music:fav' %}
But I dont know why this is showing this error:
但我不知道为什么会显示此错误:
NoReverseMatch at /music/1/ Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['music\/(?P[^/]+)\/$']
NoReverseMatch 在 /music/1/ 反转“细节”,没有找到任何参数。尝试了 1 个模式:['music\/(?P[^/]+)\/$']
回答by Fran?ois Constant
path("<album_id>/fav/", views.fav, name="fav"),
This URL needs the album_id. Something like this:
此 URL 需要相册_id。像这样的东西:
{% url 'music:fav' 1 %}
{% url 'music:fav' album.id %}
回答by Tushortz
The reason is because your view needs an album_id
argument
原因是因为你的观点需要album_id
论证
music/views.py
音乐/views.py
def fav(request, album_id):
# then filter by album id instead of a default value of 1
song = Song.objects.get(id=album_id)
song.is_favorite = True
return render(request, "detail.html")
the trick here is that your url expects to match
这里的诀窍是您的网址希望匹配
views: fav(request,
album_id
)urlspath("
<album_id>
/fav/", views.fav, name="fav"),
意见:最爱(请求,
album_id
)urlspath("
<album_id>
/fav/", views.fav, name="fav"),