Django url参数和反向URL [英] Django url parameter and reverse URL
问题描述
我有一个看起来像这样的视图:
I have a view that looks like this:
def selectCity(request, the_city):
request.session["ciudad"] = the_city
city = request.session["ciudad"]
return HttpResponse('Ciudad has been set' + ": " + city)
还有一个看起来像这样的URL:
And a URL that looks like this:
url(r'^set/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),
现在,当我访问/set/时,我会从URL {'the_city':'gye'}的dict值中获得适当的响应,其中包含会话变量集
Now when I visit /set/ I get the appropriate response with the session variable set from the value on the dict in the url {'the_city': 'gye'}
现在,我想做的就是修改程序,以便可以从其他模板(index.html)调用"ciudad" URL并设置适当的会话变量.因此,我会使用反向URL匹配和一个类似这样的附加参数来调用它:
Now, what I would like to do is modify my program so that I can call the 'ciudad' url from a different template (index.html) and set the appropriate session variable. So I would call it using reverse URL matching with an additional argument doing something like this:
<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调用,以尝试使其正常工作,但是,我似乎无法弄清楚.我真的很感谢一些指针.
I have tried to modify the url and the views and the reverse url call in various ways to try to get this to work but, I can't seem to figure it out. I would really appreciate some pointers.
推荐答案
如果您的URL(在 urls.py
中)具有任何捕获组,则可以在url标记中传递相关的参数.>
You can pass the relevant arguments in url tag, if your url (in urls.py
) has any capturing group.
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>
这篇关于Django url参数和反向URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!