Search code examples
djangopython-3.xdjango-templatesdjango-viewsdjango-2.0

Exception Type: ValueError at /music/1/favourite/ Exception Value: invalid literal for int() with base 10: 'on'


I am new to Django and I am using it's latest version 2. I am referring to this particular tutorial https://www.youtube.com/watch?v=irH98-4eKmQ&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK&index=24

I am getting this error. I tried a lot but couldn't fix the issue. ValueError at /music/1/favourite/

 Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/music/1/favourite/

Django Version: 2.0.7
Python Version: 3.6.6
Installed Applications:
['music.apps.MusicConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, 
request)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, 
**callback_kwargs)

File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite
  22.         selected_song = album.song_set.get(pk=request.POST['song'])

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, 
**kwargs)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\query.py" in get
  394.         clone = self.filter(*args, **kwargs)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\query.py" in filter
  836.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\query.py" in _filter_or_exclude
  854.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\sql\query.py" in add_q
  1253.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\sql\query.py" in _add_q
  1277.                     split_subq=split_subq,

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\sql\query.py" in build_filter
  1215.         condition = self.build_lookup(lookups, col, value)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\sql\query.py" in build_lookup
  1085.         lookup = lookup_class(lhs, rhs)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\lookups.py" in __init__
  18.         self.rhs = self.get_prep_lookup()

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\lookups.py" in get_prep_lookup
  68.             return self.lhs.output_field.get_prep_value(self.rhs)

File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- 
packages\django\db\models\fields\__init__.py" in get_prep_value
  947.         return int(value)

Exception Type: ValueError at /music/1/favourite/
Exception Value: invalid literal for int() with base 10: 'on'

This is my details.html (template)

<img src="{{ album.album_logo}}">

<h1>{{ album.album_title }}</h1>
<h2>{{ album.artist }}</h2>

{% if error_message %}
	<p><strong>{{ error_message }}</strong></p>
{% endif %}

<form action="{% url 'music:favourite' 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_favourite %}
				<img src="random_img.png"/>
			{% endif %}
		</label><br>
	{% endfor %}
	<input tye="submit" value="Favourite">
</form>

This is my view.py

from django.shortcuts import render, get_object_or_404
from .models import Album, Song

def index(request):
    all_albums = Album.objects.all()
    context={
            'all_albums':all_albums,
        }
    return render(request, 'music/index.html',context)

def detail(request,album_id):
    album = get_object_or_404(Album, pk=album_id)
    return render(request, 'music/detail.html',{'album':album})

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

Solution

  • There are some problems with the following line in your template:

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

    The two important problems are:

    1. you do not close the tag (with >); and
    2. you forgot the = for the value attribute: it should be value="{{ song.id }}" instead of value"{{ song.id }}".

    So when we fix those, we get:

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

    Since you thus had an error with the value attribute, according to the browser, there was no value="..." attribute, and thus it did a "* fallback*" to 'on' as a default string so to speak.