0
votes

I have a template file and i want to use url tag in my template file.

Html Tag <input type="text" id="test_id" value="12" />

The url is something like this

url(r'^check/(?P<code>[a-zA-Z\d]+)/(?P<test_value>[a-zA-Z\d]+)/$',
    'test_code',
    name='test_code'
),

template file with javascript code in it.

`var value1 = $('#test_id').val()`;
`var value2 = $('#test_id').val()`;

'{% url "test_code" code=value1 test_value=value2 %}'

You can see i have use the url tag and i am not able to set the value1 and value2 from the html tags values. Is there a way that i can pass the html tag values into keyword arguments of the url tag.

2
This isn't a question about keyword arguments.Daniel Roseman

2 Answers

0
votes

Not in this way. Because the template is rendered before it's sent to the user. So at the time of rendering, the value of input is not known yet. But also, template rendering won't run javascript.

What you could do is assign url with javascript on the client side. Similar with what you did, but you have to connect it to some action. $(document).ready if the input is already filled, or $(value1).on('change') if you are waiting for user's interaction.

0
votes

The template tag is evaluated on the server side when Django renders the template. Once the JavaScript code is executed on the client side, template tags are no longer visible, you just have the resulted URL string.

If you want to insert a JavaScript value in the URL, you have two options:

  1. Passing the values as GET arguments:

'{% url "test_code" %}'+'?code=value1&test_value=value2'

  1. Generating the URL with temporary keyword arguments and replacing them with JavaScript values later on:

var url = '{% url "test_code" code="code_value" test_value="test_value" %}'; url.replace("code_value", value1); url.replace("test_value", value2);