0

Im trying to have a dynamic url dispatcher such as:

"{% url 'url_name' 'variable' %}" where variable is set dynamically within my javascript.

What I want to do is basically redirect to a different page when a <select> value is changed.

$(document).ready(function() {
  $('#select').change(function() {
      var id = $('#select').val();
      window.location.replace("{% url 'url_name' 'id' %}");
  });
});

I can't do it with a simple string concat as such: "{% url 'url_name' '" + id + "' %}" as it returns this error Reverse for 'url_name' with arguments '('" + id + "',)' not found.

The select itself is being filled with backend data:

<select id="select">
  {% for item in list %}
  <option value="{{item.id}}">{{item.name}}</option>
  {% endfor %}
</select>

I cant figure out what the syntax for this is.

1 Answer 1

4

The problem is js runs in browser and django on server so you can't resolve that expression using the two languages that run in different environments and at different times

You could use a data- attribute on each <option> to print the url to

<select id="select">
  {% for item in list %}
  <option data-url="{% url 'url_name' item.id %}" value="{{item.id}}">{{item.name}}</option>
  {% endfor %}
</select>

JS

$('#select').change(function() {
  var url = $(this).find('option:selected').data('url');
  window.location.replace(url);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.