NoReverseMatch URL using Django
Currently getting a NoReverseMatch error and not sure why. Here's the error message and relevant code:
Error: Error during template rendering In template C:....<Folder><Project>\userapp\templates\userapp\details.html, error at line 11
Reverse for 'favourite' with arguments '('',)' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/favourite\Z']
urls.py
app_name = 'userapp'
path('music/<int:album_id>/favourite/', views.favourite, name='favourite')
views.py
def favourite(request, album_id):
albums = get_object_or_404(Album, pk=album_id)
try:
selected_song = albums.song_set.get(pk=request.POST['song'])
except (KeyError, Song.DoesNotExist):
return render(request, 'userapp/details.html', {
'albums': albums,
'error_message': "You did not select a valid song",
})
else:
selected_song.is_favourite = True
selected_song.save()
return render(request, 'userapp/details.html', {'albums': albums})
details.html
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
line 11 - <form action ="{% url 'userapp:favourite' album.id %}" method="post">
{% csrf_token %}
{% for song in albums.song_set.all %}
<input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}">
<label for="song{{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favourite %}
<img src="https://i.imgur.com/b9b13Rd.png"/>
{% endif %}
</label><br>
{% endfor %}
<input type="submit" value="Favourite">
</form>
You context variable is named albums
and not album
.
So you change the variable in html:
<form action ="{% url 'userapp:favourite' albums.id %}" method="post">
Or you rename averywhere albums
to album
, because is not a collection of albums, it is juste one album.