Python Django 得到了一个意外的关键字参数“id”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37254829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:07:35  来源:igfitidea点击:

Django got an unexpected keyword argument 'id'

pythondjango

提问by Ula

I'm trying to create a phonebook in Django. My urls.py:

我正在尝试在 Django 中创建一个电话簿。我的 urls.py:

    urlpatterns = [
    url(r'^$', views.people_list, name='people_list'),
    url(r'^(?P<id>\d)/$', views.person_detail, name='person_detail'),
]

views.py:

视图.py:

def people_list(request):
    people = Person.objects.all()
    return render(request, 'phonebook/person/list.html', {'people': people})


def person_detail(request, person):
    person = get_object_or_404(Person, id=person)
    return render(request, 'phonebook/person/detail.html', {'person': person})

from models.py:

来自models.py:

def get_absolute_url(self):
    return reverse('phonebook:person_detail', args=[self.id])

and list.html:

和列表.html:

{% block content %}
<h1>Phonebook</h1>
{% for person in people %}
<h2>
    <a href="{{ person.get_absolute_url }}">
        {{ person.name }} {{ person.last_name }}
    </a>
</h2>
<p class="where">
{{ person.department }}, {{ person.facility }}
    </p>
{{ person.phone1 }}<br>
{% endfor %}
{% endblock %}

The index looks ok but when I try click on links to get person_detail site I get this message:

索引看起来不错,但是当我尝试单击链接以获取 person_detail 站点时,我收到以下消息:

TypeError at /phonebook/4/ person_detail() got an unexpected keyword argument 'id' Request Method: GET Request URL: http://127.0.0.1:8000/phonebook/4/Django Version: 1.9.6 Exception Type: TypeError Exception Value: person_detail() got an unexpected keyword argument 'id'

TypeError at /phonebook/4/ person_detail() 得到了一个意外的关键字参数 'id' 请求方法:GET 请求 URL:http: //127.0.0.1:8000/phonebook/4/ Django 版本:1.9.6 异常类型:TypeError 异常值:person_detail() 得到了一个意外的关键字参数“id”

I have and 'id' argument in urls.py and in function to get_absolute_url. I don't understand what's wrong.

我在 urls.py 和 get_absolute_url 函数中有和 'id' 参数。我不明白出了什么问题。

回答by Klaus D.

Your parameter ?P<id>in the URL mapping has to match the arguments in the view def person_detail(request, person):

您的参数?P<id>中的URL映射必须在视图中匹配的参数def person_detail(request, person):

They should both be idor both person.

它们都应该是id或两者都是person

回答by alecxe

You should fix the view and use the idargument name instead of person:

您应该修复视图并使用id参数名称而不是person

def person_detail(request, id):