在這裏,我得到的ValueError在/ music/4/favorite/ int() 「ValueError at/music/4/favorite/invalid literal for int()with base 10:''
Request Method: POST
Request URL: http://127.0.0.1:8000/music/4/favorite/
Django Version: 1.10.5
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: ''
Exception Location: /usr/local/lib/python2.7/dist- packages/django/db/models/fields/__init__.py in get_prep_value, line 946
Python Executable: /usr/bin/python
Python Version: 2.7.12
Python Path:
['/home/user/python/official-django-tutorial/MusicApp',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/home/user/.local/lib/python2.7/site-packages',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
Server time: Tue, 24 Jan 2017 15:13:57 +0530
下面是該項目
from django.http import HttpResponse
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 favorite(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/detail.html',{"album":album,"error_message":"You Did Not Selected a valid Message"})
else:
selected_song.is_favorite=True
selected_song.save()
return render(request,'Music/detail.html',{"album":album,})
這裏view.py是這一個細節模板,
<img src="{{ album.album_logo}}">
<h1>{{ album.album_title }} </h1>
<h3>{{ album.artist }}
<h4>Here are the Available Songs</h4>
{% if error_message %}
<p>{{error_message}}</p>
{% endif%}
<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="{{ songs.id }}">
{{song.song_title}}
<!label for="{{forloop.couter}}"{{song.song_title}}></label>
{% if song.is_favorite %}
<img src="http://i.imgur.com/b9b13Rd.png">
{% endif %}
<br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
我該如何解決這個問題?謝謝你
看起來你的代碼沒有處理'request.POST ['song']'是一個空字符串''''的情況。 – Alasdair
空串?爲什麼? – Ananthu