I have an ajax file which calls the url from the urls.py
which gets the json data from the views.py
but when I run the server it just shows Not Found:/dept-json/
I did manage to get it to work using the django snippet {% url 'accounts:dept-json'%}
However I do not want this since I need to get and pass the variable from the dept-json data
to another ajax url which is:
url:`/prog-data/${selectedDept}/`
I have read here that you can't pass variables in ajax like {% url 'accounts:prog-json' department%}
how do I manage to do this?
here is my code:
main.js
//First ajax
$.ajax({
type: 'GET',
url: "/dept-json/",
// url: "{% url 'accounts:dept-json'%}",
success: function(response){
console.log(response)
},
error: function(error){
console.log(error)
}
})
//Second ajax
$.ajax({
type: 'GET',
url: `/prog-data/${selectedDept}/`,
success: function(response){
console.log(response)
},
error: function(error){
console.log(error)
}
})
urls.py
path('dept-json/', get_json_dept_data, name='dept-json'),
path('prog-json/<str:department>/', get_json_prog_data, name='prog-json'),
views.py
def get_json_dept_data(request):
qs_val = list(Department.objects.values())
return JsonResponse({'data':qs_val})
def get_json_prog_data(request, *args, **kwargs):
selected_department = kwargs.get('department')
obj_prog = list(Program.objects.filter(department__name=selected_department).values())
return JsonResponse({'data':obj_prog})
CodePudding user response:
You need to send the data in your ajax request like so:
$.ajax({
url: "{% url 'accounts:prog-json'%}",
data: {
'department': selectedDept
},
success: function(response){
console.log(response)
},
error: function(error){
console.log(error)
}
})
And then on your view you can access that argument from the request:
def get_json_prog_data(request):
selected_department = request.GET.get('department')
obj_prog = list(Program.objects.filter(department__name=selected_department).values())
return JsonResponse({'data':obj_prog})
I dont believe you need the parameter in your url, so you should be able to just remove that as we are sending the data in the ajax request.
path('prog-json/', get_json_prog_data, name='prog-json'),