0

I have one URL in urls.py file as given below:-

urlpatterns = [
        ........
      path('edit_student/<student_id>', views.edit_student, name="edit_student"),
      path('populate_sections', views.populate_sections, name="populate_sections"),
      ..........
      ]

In views.py file edit student function is defined as follows:

@login_required
def edit_student(request, student_id):
 form = UpdateStudentForm()
 context = {
           "form": form
}
return render(request, "edit_student.html", context)

Now the template edit_student.html has a Ajax call:-

$("#id_class_name").change(function(){ var class_name = $(this).val();

    $.ajax({
        url: 'populate_sections',
        type: 'GET',
        data: {class_name:class_name},
        dataType: 'json',
        success: (data) => {
            $("#id_section_name").empty();
            for( var i in data.context){
                $("#id_section_name").append("<option value='"+data.context[i].id+"'>"+data.context[i].name+"</option>");
            }
        }
    });
});

The views.py file function populate_section is declared as follows:-

@login_required
def populate_sections(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax:
    if request.method == 'GET':
        class_name = request.GET.get("class_name")
        class_object = Classes.objects.get(id=class_name)
        sections = Sections.objects.filter(classes=class_object)
        return JsonResponse({'context': list(sections.values())})
    return JsonResponse({'status': 'Invalid request'}, status=400)
else:
    return HttpResponseBadRequest('Invalid request')

Whenever i change the field which triggers Ajax function call i am getting the value error:

ValueError at /edit_student/populate_sections

Exception Value:
Field 'id' expected a number but got 'populate_sections'.

I understand that it is expecting the student id but how to do that.

Thanks & Regards Neha Singh

BullHump
  • 1
  • 1
  • Does this answer your question? [Why would a developer place a forward slash at the start of each relative path?](https://stackoverflow.com/questions/7613274/why-would-a-developer-place-a-forward-slash-at-the-start-of-each-relative-path) – Abdul Aziz Barkat Sep 27 '22 at 12:42
  • Assume your current url is `edit_student/` and when you say `url: 'populate_sections'` this being a relative url resolves to `edit_student/populate_sections`. You should really write `url: '/populate_sections'` with a forward slash in the url. – Abdul Aziz Barkat Sep 27 '22 at 12:45
  • Thanks for your prompt reply. This solved my problem.Thanks Again – BullHump Sep 27 '22 at 13:39

0 Answers0