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

Question:

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[^/]+)/$’]

Asked By: Vishal Ghosh

||

Answers:

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 %}
Answered By: François Constant

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.py

def fav(request, album_id):

urls

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

Answered By: tushortz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.