In my project I have a lot of Ajax methods, with external client-side scripts (I don't want to include JavaScript into templates!) and changing URLs is kind of pain for me because I need to change URLs in my Ajax calls manually.
Is there is some way to emulate the behavior of {% url %}
templatetag in JavaScript?
For example, print urlpatterns starting with ^ajax
and later in scripts replace patterns with their actual values?
That's what on my mind, and my question is - are there any common practices to do things like that? Maybe some reusable applications? Also I will be happy to read any advices and relevant thoughts you have.
Update 1: I'm talking about computed URLs, not static ones:
url(r'^ajax/delete/(?P<type>image|audio)/(?P<item_id>\d+)/from/set/(?P<set_id>\d+)/$', 'blog.ajax.remove_item_from_set'),
First, you should name your url:
Then you could pass urls as variables to your module:
You could use tokens in your url:
Notice that your token should match the regex type to resolve successfully (I can't use
{item_id}
as token because it's defined with\d+
).I was a little bit unsatisfied with this solution and I ended by writing my own application to handle javascript with django: django.js. With this application, I can do:
I have found this cool django app called Django JS reverse
https://github.com/ierror/django-js-reverse
If you have a url like
Then you do
The result is
I created a mechanism that builds a list of url patterns in your Django project and outputs that in a Javascript file. It is a fork of django-js-utils.
The repo link is here: https://github.com/Dimitri-Gnidash/django-js-utils