Reputation: 43
TypeError during django project
Got this message on the error page:
TypeError at /music/1/
detail() got an unexpected keyword argument 'pk'
Request Method: GET Request URL: http://127.0.0.1:8000/music/1/ Exception Type: TypeError
detail() got an unexpected keyword argument 'pk'
This is my music\view.detail function
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'music/detail.html', {'album':album})
And this is a form in my detail.html which might raise the error:
<form action="{% url 'music:favorite' album.id %}" method="post">
{% csrf_token %}
{% for song in album.song_set.all %}
<!-- forloop.counter indicates how many times the for tag has gone
through its loop -->
<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://i.imgur.com/b9b13Rd.png" />
{% endif %}
</label><br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
And this is my urls.py
from django.conf.urls import url
from . import views
app_name = 'music'
urlpatterns = [
# /music/
url(r'^$', views.index, name = 'index'),
# /music/<album_id>/
url(r'^(?P<pk>[0-9]+)/$', views.detail, name = 'detail'),
# /music/<album_id>/favorite
url(r'^(?P<album_id>[0-9]+)/favorite/$', views.favorite, name =
'favorite'),
]
Upvotes: 3
Views: 13616
Reputation: 174718
In your pattern, the parameter is called pk
for the detail view:
# /music/<album_id>/
url(r'^(?P<pk>[0-9]+)/$', views.detail, name = 'detail'),
^^ - this is the name of the parameter that it is looking for
However, your detail view has album_id
:
vvvvvvvv - this is not matching pk
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'music/detail.html', {'album':album})
Since those two don't match, you get the error because django cannot find a method that matches the url pattern. To fix it, make sure your pattern matches the method definition.
Upvotes: 5