Skip to content
Advertisement

Django | JS variable inside dynamic URL

I’m trying to pass a javascript variable inside a dynamic url using Django. I have the following path

path('task-update/<str:pk>/', updateTask, name='task-update'),

I’m able to retrieve the “Task” fields I created (id, title, description, …) depending on what task I select inside the HTML (this is done using AJAX and the Django-REST Framework). However, I’m having some trouble on rendering javascript values inside dynamic urls

var url = `{% url 'task-update' pk=${activeItem.id} %}`

The ${activeItem.id} is where I’m having some trouble, I tried assigning it to a variable and passing that into the URL but it doesn’t work.

A workaround I’ve been using is

var url = `http://127.0.0.1:8000/task-update/${activeItem.id}/`

however I’d like to use django’s template tags

Advertisement

Answer

After searching for quite a bit this was the best neat-looking solution I found (also the only one): django-js-urls.

Just pip install django-js-urls and add ‘js_urls’ to your INSTALLED APPS.

Afterwards add simply add JS_URLS to your settings.py file and put the names of the paths you’d like to use. In my case I only added task-update, it looks something like this

JS_URLS = (
    'task-update',
)

Then, all you need to do is add the following in the URLs root module

from js_urls.views import JsUrlsView

urlpatterns = [
    # other urls
    url(r'^js-urls/$', JsUrlsView.as_view(), name='js_urls'),
]

And include the following js in the template

<script src="{% url 'js_urls' %}" type="text/javascript"></script>

URLs can be used using the window.reverse function

var url = window.reverse('task-update', { pk: activeItem.id });
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement