csserrs
csserrs

Reputation: 23

Django ajax wouldn't work when in separate file

I have django site that uses ajax. When i use javascript inside html document <script>...</script> everything works fine. But when i move javascript to separate file everything (all javascript) works great, but ajax. On every ajax request i get: 404 (Not Found) and it always show the line of the document where ajax starts. My urls are like this:

url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)/dodaj$', views.create_exam, name="create_exam"),

In views:

def create_exam(request, letnik_id, classes_id, subject_id):
...

and ajax url:

$.ajax({
    url: "{% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}",
...

Maybe if in separate file the {% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %} wont work? But is there any other way to point to the url? What am i doing wrong?

Upvotes: 0

Views: 630

Answers (2)

theWanderer4865
theWanderer4865

Reputation: 871

What's wrong:

You're trying to use a Django Template tag ({% url ... %}) outside of a template.

Fixing it:

You can do something like dump out a bunch of data into your HTML and attach it to the window object in the browser

<script>
window.page_data = {
  someUrl: {% url ... %}
};
</script>

Then use your other scripts, accessing the data from the window...

$.ajax(window.page_data.someUrl)

Or, you can embed the URL in the markup with a data attribute

<div data-url="{% url ... %}">

Then extract it from the element in Javascript.

As your project grows in complexity, your API should pass along the data you need to perform each action on a resource. Just beware of coupling your client with your server unnecessarily. That is, don't hard code urls since they may change and this will cause some unexpected breakage. If you have to hard code anything, make sure to do it in only one place and make a note somewhere to fix that at some point.

Upvotes: 1

Pablo Fernandez
Pablo Fernandez

Reputation: 436

You answered your own question. In a separate JS file a django template tag won't work. It only works on the templates rendered by a Django view. You may need to find another way around.

I'm not sure if this is the best approach but you may declare a global js variable in the template with the url and then use it in your js file. I really don't know if its the best approach but I think it will work.

In your html before you import the js file before you declare the variable:

MY_URL = "{% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}";
<script src="myscripts.js"></script>

Upvotes: 2

Related Questions