Home > Software engineering >  Dynamic action URL in Django Template
Dynamic action URL in Django Template

Time:01-25

I have a form in Django and would like to add the correct id at the end of the URL. I am not sure how to add the ID at the end dynamically however. Here's some example code.

{% for dealer_payment_account in dealer.dealerpaymentaccount_set.all %}
<p>Account: {{ dealer_payment_account.last_4_digits }}</p>
  <form id="verifyDealerBankAccountForm" action="/verify-dealer-payment-account/{{ dealer_payment_account.id }}" method="POST">
    <div >
      <label>Payment</label>
      <input type="text" name="amount">
    </div>
    <button type="submit">Submit</button>
  </form>
{% endfor %}

Specifically I am wondering how to format this:

action="/verify-dealer-payment-account/{{ dealer_payment_account.id }}"

so that I can add the dealer_payment_accound.id to the end of each form.

CodePudding user response:

Modify your form in the template this way:

<form action="{% url 'verify_dealer_payment_account' dealer_payment_account.id %}">

where: verify_dealer_payment_account is a name of the URL pattern.

Docs: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#url

CodePudding user response:

Have you tried urlnamespace

<form id="verifyDealerBankAccountForm" action="{% url 'your-verify-dealer-payment-account' dealer_payment_account.id %}" method="POST">

NOTE : please add your respective url name in your-verify-dealer-payment-account

For e.g.

path('verify-dealer-payment-account/<str:payment_account_id>',  views.your_view_name, name='your-verify-dealer-payment-account' )

The url name your-verify-dealer-payment-account is used in template.

  •  Tags:  
  • Related