Reputation: 325
I'm making the website using django, python and javascript.
I get an error
'Not found: /schedule/{% url 'schedule_delete' %}' when I use the ajax in js file
fullcalendar.js
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
var start = event.start;
var id = event.id;
var title = event.title;
var allData = {'csrfmiddlewaretoken': '{{ csrf_token }}', "id":id, "start":start, "title":title};
$.ajax({
url: "{% url 'schedule_delete' %}",
type: "POST",
data: allData,
dataType: "json",
success: function(response){
alert("success!");
$('#used_session'+id).html(response.used_session);
},
error:function(error){
alert("fail!");
}
});
}
urls.py
from django.conf.urls import url
from . import views
urlpatterns= [
url(r'^$', views.home, name='home'),
url(r'^schedule_delete/$', views.schedule_delete, name='schedule_delete'),
]
I also made schedule_delete in views.py.
Why url is wrong?? The same url format was okay in the other template. Is url foramt different depending on the django template or js file??
Any help will be very helpful to me, thanks!
Upvotes: 2
Views: 2667
Reputation: 6379
Your javascript files have no access to a django context, since you are only rendering html files through django. What you need to do is put your javascript inline in your templates to be able to access the {% url %} template tag.
An alternative way is to create for example a data-url html attribute which you set to your url, and access that attribute in your javascript file.
Edit:
I am not sure what your html looks like but I assume your eventElement is a button.
<button data-url="{% url 'schedule-delete' %}"></button>
When you click the button your event handler is called in your js file:
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
...
$.ajax({
url: $(eventElement).data('url'),
...
Upvotes: 3
Reputation: 4634
You are making a request to the url /schedule/schedule_delete/
but it looks like your urls.py is setup only to handle the url /schedule_delete/
. Are you including the schedule urls.py from a main urls.py?
Also as the other answerer noted, you can't use django template variables in a javascript file.
Upvotes: 0
Reputation: 2257
you can not use "{% url 'schedule_delete' %}"
in your js file. You first need to take this url in an input in your html form and then read it using javascript or jquery.
In html write.
<button ... id="ajax-button" data-ajax-target="{% url 'named-url' %}">
and in javascript simply do
$.post($("#ajax-button").attr("data-ajax-target"), ... );
this is just an example you can do similar in other ways also.
Upvotes: 2