tasstra
tasstra

Reputation: 23

Error while submitting form in Django. ValueError: invalid literal for int() with base 10: ''

I can't get the following problem solved even with the answers to related questions on this site.

At the moment I am doing the Django tutorial but got stuck with the form. The following error, that i get whem submitting a favorite song, is bugging me:

ValueError: invalid literal for int() with base 10: ''

I tried everything i could think of (e.g. selected_song = album.song_set.get(pk= int(request.POST['song'])) and googled looking for an answer but i can't seem to fix it. I appreciate any help.

detail.html

<form action="{%  url 'music:favorite' album.id %}" method = "post">
    {%  csrf_token %}
    {% for song in album.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_favorite %}
                <img src="http://http://i.imgur.com/b9b13Rd.png" />
            {% endif %}
        </label><br>
    {% endfor %}
    <input type="submit" value="Favorite">
</form>

views.py

def favorite(request, album_id):
    album = get_object_or_404(Album, pk = album_id)
    try:
        selected_song = album.song_set.get(pk= int(request.POST['song']))
    except (KeyError, Song.DoesNotExist):
        return render(request, 'music/detail.html', {
            'album':album,
            'error_message': "You didn't select a valid song"
            })
    else:
        selected_song.is_favorite = True
        selected_song.save()
        return render(request, 'music/detail.html', {'album': album})

Upvotes: 2

Views: 299

Answers (1)

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

In your template you are doing

<input type = "radio" id = "song{{ forloop.counter }}" name = "song" value = "{{ song_id }}" />

{{song_id}} is None in this case. You need to use {{song.id}}.

<input type = "radio" id = "song{{ forloop.counter }}" name = "song" value = "{{ song.id }}" />

So a blank string '' is passed to your view, which you are trying to pass to int hence the error.

Upvotes: 3

Related Questions