Django将模型ID添加到URL

时间:2014-09-08 19:30:46

标签: python django django-templates

我有一个列出位置的仪表板。然后,您可以单击位置以获取该位置的更多详细信息。我收到404错误消息。

http://127.0.0.1:8000/locations/get//

这是我遇到问题的部分代码。

urls.py

url(r'^accounts/loggedin/locations/all/$', 'assessments.views.locations'),
url(r'^accounts/loggedin/locations/get/(?P<location_id>\d+)/$', 'assessments.views.location'),

views.py

def locations(request):
    return render_to_response('dashboard/locations.html', {'locations': Location.objects.all() })

def location(request, location_id=1):
    return render_to_response('dashboard/location.html', {'location': Location.objects.get(id=location_id) })

locations.html

{% for p in locations %}
    <tr>
        <td><a href="/locations/get/{{ location.id }}/">{{ p.landlord_agent }}</a></td>
        <td><a href="/locations/get/{{ location.id }}/">{{ p.id }}</a></td>
    </tr>
{% endfor %}

说实话,我不知道为什么它会是location_id,因为数据库字段只是id,但这就是指南如何让我这样做并将其改为id只是似乎没有差异

2 个答案:

答案 0 :(得分:4)

问题出在模板内部。您有一个名为p的循环变量,而不是location

location.id替换为p.id


或者,更好地将此变量称为location - 更具可读性和显性。

完整的模板代码:

{% for location in locations %}
    <tr>
        <td><a href="/locations/get/{{ location.id }}/">{{ location.landlord_agent }}</a></td>
        <td><a href="/locations/get/{{ location.id }}/">{{ location.id }}</a></td>
    </tr>
{% endfor %}

答案 1 :(得分:1)

编辑您的app / urls.py:

url(r'^locations/get/(?P<location_id>[\d]+)/$', 'assessments.views.location')