Using a Django URL Tag in an AJAX Call

There are many posts and pages on the use of Django and AJAX, and I have read hundreds in the last day or so am looking for an answer to this question. Short review:

May examples show hardcoded URLs, for example:

$.post("/projects/create/", {"name" : name}, function(data) {... 

or some use the URL pattern tag, but without parameters:

 $.post("{% url create_project %}", {"name" : name}, function(data) {... 

However, I would like to include a Django style parameter in the URL. Here is my url definition:

 url(r'ajax/entity_name/(?P<pk>\w+)/$',EntityAjaxView.as_view(),name='entity_name'), 

Yes, I use a class based view and it is based on DetailView. This view looks by default for the pk value, which should be specified in the URL, and in a regular template I would use:

 {% url entity_name id_number %} 

to provide a link. In my code, I want to get the value entered in the input field for the pk value. Here is a snippet of my JavaScript (which doesn't work):

 var id_number = $('#id_endowmententity_set-' + rownum + '-id_number').val() $.ajax({ type: "GET", url: '{% url entity_name id_number %}', 

So my question is: can I use the URL pattern tag with the value from the input field?

(I know that I could use POST instead of GET and pass id_number in the POST data, but this will not work with DetailView.)

Thanks in advance for your help.

+7
ajax django
source share
1 answer

Django is a server application. Javascript is the client side. Django templates are displayed on the server, so {% url entity_name id_number %} is evaluated on the server side, and then the value is returned to the client. Because of this, you cannot combine Django templates with javascript. However, there are a few things you can solve to solve your problem.

Since you are making an ajax call, and the ajax call depends on some user input, usually the best route is for the client to send any type of user input to the server - either using querystring (thing after ? In the URL) or by sending POST data. So, the simplest thing is to change your URL so that it does not include pk in the URL, but for presentation, to get this as part of the GET or POST data.

 url(r'ajax/entity_name/$', EntityAjaxView.as_view(), name='entity_name'), 

and view (sorry, I'm not familiar with class based views):

 def entity_name(request): pk = request.GET.get('pk') ... 

It seems to me that this is the most elegant solution. If, however, you absolutely need to create a client-side URL, you can create a server-side URL for the template, and then replace all the parts you need on the client side to get the full URL. However, this requires more maintenance and is therefore more error prone. A simple js example of this approach:

 var id_number = $('#id_endowmententity_set-' + rownum + '-id_number').val(), url = '{% url entity_name 0 %}'.replace('0', id_number); $.ajax({ type: "GET", url: url, ... }); 
+10
source share

All Articles