Django: AJAX and path params
<p>I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.</p>

<p>Say we have an url with a path param that maps to a particular view:</p>

<pre><code>url(r'^post/(?P&lt;post_id&gt;\d+)/$', TemplateView.as_view('post.html'))
</code></pre>

<p>And then the <code>post.html</code> includes a script that performs an AJAX request to fetch the post as JSON:</p>

<pre><code>post.html

&lt;script src="{{ STATIC_URL }}/js/post.js"&gt;&lt;/script&gt;
&lt;div id="post-container"&gt;&lt;/div&gt;
</code></pre>

<p>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.</p>

<pre><code>post.js

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

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

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

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

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

<p>then in your can template call that url in this way <code>{% url 'my_name' object.pk  %}</code>  see <a href="https://docs.djangoproject.com/es/1.10/ref/templates/builtins/#url" rel="nofollow">this</a> for more.</p>

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

<pre><code>&lt;srcipt&gt;var foo={{django_var}}&lt;/script&gt;
&lt;script src="{{ STATIC_URL }}/js/post.js"&gt;&lt;/script&gt;
</code></pre>

<p>and then use the variable <code>foo</code> in the js.</p>

python json ajax django