Django - getting Error “Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:” when using {% url “music:fav” %}

旧街凉风 提交于 2020-01-02 03:52:05

问题


I am learning django framework from last 4 days. Today I was trying to retrieve a URL in HTML template by using

{% url "music:fav" %}

where I set the namespace in music/urls.py as

app_name= "music"

and also I have a function named fav(). Here is the codes:

music/urls.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

def fav(request):
    song = Song.objects.get(id=1)
    song.is_favorite = True
    return render(request, "detail.html")

in detail.html I used

{% 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[^/]+)\/$']


回答1:


path("<album_id>/fav/", views.fav, name="fav"),

This URL needs the album_id. Something like this:

{% url 'music:fav' 1 %}
{% url 'music:fav' album.id %}



回答2:


The reason is because your view needs an album_id argument

music/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)

urls path("<album_id>/fav/", views.fav, name="fav"),



来源:https://stackoverflow.com/questions/47944443/django-getting-error-reverse-for-detail-with-no-arguments-not-found-1-patt

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