Reverse for 'favourite' with arguments '('',)' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/favourite/\\Z']

I get NoReverseMatch error message and not sure why

Error message:

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' 

urlpatterns = [
  ......
    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>

This is telling you that when trying to construct the “favourite” url, the only argument used is “”, an empty string.

Looking at that line in the template:

<form action ="{% url 'userapp:favourite' album.id %}" method="post">

You’re passing album.id so that is none/empty/non-existent.

In your view you’re passing this context to the template:

{'albums': albums}

So there’s no album variable.

Maybe there’s more to the template, and you expect there to be an album variable, but you haven’t shown that, so I’m unable to help further at this point.

1 Like