简体   繁体   中英

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). 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})

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:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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