简体   繁体   中英

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

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

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 %}

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"),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM