dabadaba dabadaba - 2 months ago 11
Ajax Question

Django: AJAX and path params

I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.

Say we have an url with a path param that maps to a particular view:

url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'))


And then the
post.html
includes a script that performs an AJAX request to fetch the post as JSON:

post.html

<script src="{{ STATIC_URL }}/js/post.js"></script>
<div id="post-container"></div>


This could be the js file. Let's say we do it this way because the post (as JSON) needs to be used in a js plugin to display it in a particular fancy manner.

post.js

$.ajax({
url: '/post/??post_id??',
contentType: 'application/json'
})
.done(function(post_data) {
togglePlugin(post_data);
});


My main concern is how to figure out what
post_id
is from the js file in order to make the appropriate call.

How are these parts usually connected in Django? The parts I am talking about are urls, path params, views and ajax.

Answer

To get urls from your template you should use {% url %} template tag, for that you should add a name to your url:

url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'), name='my_name)

then in your can template call that url in this way {% url 'my_name' object.pk %} see this for more.

when you work with different file for your js, and you want to pass django variables, you should declare a <script> before import the js file, and there declare your variable:

<srcipt>var foo={{django_var}}</script>
<script src="{{ STATIC_URL }}/js/post.js"></script>

and then use the variable foo in the js.

Comments