Skip to main content
 首页 » 编程设计

python之将 url 模式作为 django 中的输入

2024年10月01日28zengkefu

假设我有一个变量:

a=['https://www.google.com','https://www.go.com','https://www.ogle.com'] 

我有一个模板 dome.html:

   {%for i in a %} 
 
   <a href=/link/{{a}}>Click</a><br/> 
 
   {%endfor%} 

我的 views.py 如下:

 def someview(request,id): 
    do something with input (id) 

现在我想配置我的 urls.py,以便它与我的 views.py 通信,后者将 {{a}} 作为输入 (id)。

url(r'^/link/(url-regex)',someview , name="someview"), 

现在我真的想要 url-regex,我将如何配置它。请帮忙

请您参考如下方法:

# urls.py 
from django.conf.urls import url 
 
from . import views 
 
urlpatterns = [ 
    url(r'^link/(?P<id>[0-9]+)/$'', views.someview), 
] 

然后在你的views.py

# views.py 
 
def someview(request,id): 
    do something with input (id) 

这是一个很常见的模式,即explained thoroughly by the official docs ,所以我建议复习一下。