django项目中的TypeError
在错误页面上收到此消息:
类型错误/music/1/
detail() 得到了一个意外的关键字参数 'pk'
请求方式:GET 请求网址:http://127.0.0.1:8000/music/1/ 异常类型:TypeError
detail() 得到了一个意外的关键字参数 'pk'
这是我的 music\view.detail 函数
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'music/detail.html', {'album':album})
这是我的 detail.html 中的一个表单,它可能会引发错误:
<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>
这是我的 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'),
]
最佳答案
在您的模式中,详细 View 的参数称为 pk
:
# /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
但是,您的详细 View 有 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})
由于这两个不匹配,您会收到错误,因为 django 找不到与 url 模式匹配的方法。要修复它,请确保您的模式与方法定义匹配。
关于python - 类型错误 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38084964/