【问题标题】:Django url parameter and reverse URLDjango url 参数和反向 URL
【发布时间】:2012-12-05 23:48:13
【问题描述】:

我的视图如下所示:

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/ 时,我会从 url {'the_city': 'gye'} 中的 dict 上的值设置会话变量得到适当的响应

现在,我想做的是修改我的程序,以便我可以从不同的模板 (index.html) 调用“ciudad”网址并设置适当的会话变量。 所以我会使用反向 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 调用以尝试使其正常工作,但我似乎无法弄清楚。 我真的很感激一些指点。

【问题讨论】:

    标签: python django django-templates django-views django-urls


    【解决方案1】:

    如果您的 url(urls.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>
    

    【讨论】:

    • 是的,这是完美的,谢谢!一个简单的问题,\w+ 部分或正则表达式是做什么的?
    • 请看here\w+表示匹配任意字母数字字符和下划线;这相当于集合 [a-zA-Z0-9_]
    【解决方案2】:

    查看captured parameters。这样的事情可能会奏效:

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

    【讨论】:

      猜你喜欢
      • 2013-01-14
      • 2015-01-07
      • 2012-11-18
      • 2021-05-29
      • 2010-11-16
      • 2023-03-25
      • 2019-11-04
      • 1970-01-01
      • 2011-10-15
      相关资源
      最近更新 更多