Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: reverse parametrized url in JavaScript

let's say one of my urlpatterns looks like this.

url('^objects/update/(?P<pk>\d+)$', views.UpdateView.as_view(), name = 'update-object'),

I need to redirect user to the update page depending on the selected object (the list of objects is populated using Ajax). So I'd like to pass that named url pattern to the JavaScript, in order to build the actual url on the client side.

Example of what I want to achieve:

  1. pass the name 'update-objects' to the function
  2. get the actual url pattern, replace (?P<pk>..) with {pk}
  3. pass the result to the javascript, resulting in : objects/update/{pk}

any tips? thanks


to make it more clear: at the moment of rendering, I can't do url reverse because the PK is not known yet. I need to make kind of javascript-urlpattern which will later be converted to the real url (i.e. my JS code will replace {pk} part with the actual pk value)

like image 871
migajek Avatar asked Dec 20 '25 09:12

migajek


1 Answers

The actual URL reversing must happen on the server side. There are several ways to do this, and the most elegant of these probably depends on how exactly your script and markup are set up for this. One thing I've done recently is to attach the URL to a logical element using HTML5 data attributes, which are easy to retrieve using jQuery. If you're not using jQuery, I'll leave it up to you to translate to pure JS. You haven't provided any code or specifics for your client-side, so I'm kind of shooting in the dark here, but maybe this will give you the idea:

Django HTML template:

<ul class="object-list">
 {% for object in objectList %}
  <li data-update-url="{% url update-objects object.pk %}">object.name</li>
 {% endfor %}
</ul>

JS:

$('.object-list').on('click', 'li' function () {
  var updateUrl = $(this).data('update-url')
  ...
});
like image 93
acjay Avatar answered Dec 23 '25 00:12

acjay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!