Django url参数和反向url

2024-09-26 18:21:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的观点:

def selectCity(request, the_city):
    request.session["ciudad"] = the_city
    city = request.session["ciudad"]
    return HttpResponse('Ciudad has been set' + ": " + city)

以及一个如下所示的URL:

url(r'^set/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),

现在,当我访问/set/I时,从url{the戥city':'gye'}中dict的值中设置会话变量,得到适当的响应

现在,我要做的是修改我的程序,以便可以从不同的模板(index.html)调用“ciudad”url并设置适当的会话变量。 因此,我将使用反向URL匹配来调用它,并使用一个附加参数执行如下操作:

  <div class="modal-body">
      <a tabindex="-1" href="{% url ciudad 'the_city':'uio' %}">Quito</a>
      <br/>
      <a tabindex="-1" href="{% url ciudad 'the_city':'gye' %}">Guayaquil</a>
  </div>

我试图通过各种方式修改url、视图和反向url调用,以使其正常工作,但是,我似乎无法解决这个问题。 我真的很感激你的指点。


Tags: thedivurlcityrequestsessiondefhref
2条回答

如果url(inurls.py)有任何捕获组,则可以在url标记中传递相关参数。

url(r'^set/(?P<the_city>\w+)/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),

然后在模板中:

<a tabindex="-1" href="{% url ciudad the_city='gye' %}">Guayaquil</a>

签出captured parameters。类似的事情可能会奏效:

url(r'^set/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),
url(r'^set/(?P<the_city>\w+)/$', views.selectCity, name='ciudad'),

相关问题 更多 >

    热门问题