[英]How to use reverse an url with extra arguments in a django template tag?
I have created a template tag in django for forms that only require a submit button, without any other fields (except the hidden csrf field). 我在Django中为仅需要一个提交按钮的表单创建了一个模板标签,而没有任何其他字段(隐藏的csrf字段除外)。 It can be used as follows:
可以如下使用:
{% button_only_form "button_text" "action/path" "optionally css classes. %}
I'm currently mainly using this for delete buttons, because delete views require sending a post request, but don't need any other data. 我目前主要将其用于删除按钮,因为删除视图需要发送发布请求,但不需要任何其他数据。
Now I'm finding myself in a situation where I need to dynamically create the action. 现在,我发现自己处于需要动态创建动作的情况。 I'm iterating over a list of items, and the action url for each item would be the result of calling
reverse("items:delete", kwargs={"item_id": item.id})
我正在遍历项目列表,每个项目的操作URL都是调用
reverse("items:delete", kwargs={"item_id": item.id})
How would I specify this for my template tag? 如何为我的模板标签指定此标签? Here's a hugely simplified version of my template:
这是我的模板的简化版本:
<ul>
{% for item in items %}
<li>
{{item.title}} - {% button_only_form "Delete" Im_not_sure_how_to_pass_the_action %}
</li>
{% endfor %}
</ul>
You can use the {% url ... as var %}
syntax to first create the url for the action and then pass it as a parameter to the button_only_form
tag: 您可以使用
{% url ... as var %}
语法来首先创建操作的url,然后将其作为参数传递给button_only_form
标记:
<ul>
{% for item in items %}
<li>
{% url "items:delete" item_id=item.id as del_url %}
{{item.title}} -
{% button_only_form "Delete" del_url "..." %}
</li>
{% endfor %}
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.