简体   繁体   English

如何将 django 模板中的参数传递给单击列表中的列表项的视图?

[英]How to pass argument from django template to views on clicking list item from list?

In my template I have a list containing some items under headings of name and id and i want to add hyperlink to each of them item and when i click an item it takes it's id as argument to the function in views.py of django and run that function.在我的模板中,我有一个包含名称和 ID 标题下的一些项目的列表,我想为每个项目添加超链接,当我单击一个项目时,它会将其 id 作为 django 的views.py 中的 function 的参数并运行即 function。

Currently my templates looks like:目前我的模板看起来像:

<html>
<head>
<body>


<table border="1" cellpadding="5" cellspacing="5">

<td>ID</td>
<td>Name</td>

{% for i in data%}

<tr>
<td>{{i.ID}}</td>
<td>{{i.Name}}</td>
</tr>

{% endfor %}

</table>

</body>
</head></html>

You can simply do a href after your td.你可以简单地在你的 td.href 之后做一个 href。 In your views you can do the function thing.在您看来,您可以做 function 的事情。 You need to define a function which takes the id argument.您需要定义一个带有 id 参数的 function 。

<html>
<head>
<body>


<table border="1" cellpadding="5" cellspacing="5">

<td>ID</td>
<td>Name</td>

{% for i in data%}

<tr>
<td>{{i.ID}}</td>
<td> <a href="/yourpath/{{i.id}}"{{i.Name}}></td>
</tr>

{% endfor %}

</table>

</body>
</head></html>



def your_function_name(request, YOUR_ID):

   # code

Also in your urls.py也在你的 urls.py


urlpatterns= [
    path('your_path/<your_id>/', views.your_function_name, name='your_name'),
]


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM