首页 文章

TypeError Django

提问于
浏览
0

django项目期间的TypeError

在错误页面上收到此消息:

TypeError at / music / 1 /

detail()得到了一个意外的关键字参数'pk'

请求方法:GET请求URL: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'),
]

1 回答

  • 1

    在您的模式中,详细视图的参数名为 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
    

    但是,您的详细信息视图有 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模式匹配的方法 . 要修复它,请确保您的模式与方法定义匹配 .

相关问题