python - 类型错误 Django

标签 python django

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/

相关文章:

python - 如何计算pyspark中的日期差异?

python - 手动实例化一个日志客户端

python - 在列表列表中查找所有 None 的最 Pythonic 方法是什么?

python - 如何在我的模型中使用 Auth 用户模型作为外键?

python - 编写一个程序,在一行代码中打印从 1 到 100(含)的整数,但是

python - 每次从每个文件中插入 2 行或更多行的多个文件

python - 在 Django Rest Framework 中的序列化程序之间混合公共(public)字段

html - 在 RSS 提要中嵌入 HTML 的最佳方式是什么?

python - Django - Stripe 订阅

Django 管理员 : Customizing the inline template (tabular. html)