将id传递给url链接 - Django

时间:2014-10-13 06:29:52

标签: python django

我需要在cluster_id页面中传递show.html,以防用户希望暂停创建的群集。我的urls.py看起来像是:

from django.conf.urls import url
from django.core.context_processors import csrf
from django.shortcuts import render_to_response

from clusters import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^register/', views.register, name='register'),
    url(r'^show/', views.show, name='show'),
    url(r'^login/', views.user_login, name='login'),
    url(r'^logout/', views.user_logout, name='logout'),
    url(r'^destroy_clusters/', views.destroy_clusters, name='destroy_clusters'),
    url(r'^halt_clusters/(?P<cluster_id>\d+)/$', views.halt_clusters, name='halt_clusters'),
    url(r'^check_log_status/', views.check_log_status, name='check_log_status'),
    url(r'^read_cluster_log/', views.read_cluster_log, name='read_cluster_log'),
]

在我的show.html我有:

{% for cluster in clusters %}
        <tr>
            <td><a href="#">{{ cluster.id }}</a></td>
            <td><a href="{% url halt_clusters cluster_id=cluster.id %}">Halt</a></td>
        <tr>
{% endfor %}

所以当我执行网页时,我有:

NoReverseMatch at /clusters/register/
Reverse for '' with arguments '()' and keyword arguments '{u'cluster_id': 19L}' not found. 0 pattern(s) tried: []

这让我抓狂!为什么我不能在那里传递id?我看了这个例子:Passing an id in Django url但它似乎并不适合我。救命? 我的Django版本为1.8.dev

1 个答案:

答案 0 :(得分:1)

在最近的Django中,您应该在标记中引用文字URL名称:

{% url "halt_clusters" cluster_id=cluster.id %}

否则Django会在您的上下文中查找halt_clusters变量,并将其值用作URL名称。

哦,虽然你不知道,但是你不必指定关键字参数名称,所以这也应该有效:

{% url "halt_clusters" cluster.id %}