[Django]-How to render a piece of data stored in an external model without refreshing the page?

2👍

Since you’re defining you endpoint in the urlpatterns[] as follows:

path('get-employee-name/<int:id>/', views.get_employee_name, name='employee_name'),

the associated view should expect id a second parameter following request; for example:

from django.http import HttpResponse
from django.shortcuts import get_object_or_404


def get_employee_name(request, id):
    employee = get_object_or_404(Salesman, id=id)
    return HttpResponse(employee.slsmn_name)

In the ajax call, I would rather use an absolute url:

var url = '/get-employee-name/' + employee_number;

(please note the leading backslash) otherwise, the visited url would be relative to the current page;
If the app’s urlpatterns in included in the root one with a suffix, add it as required:

var url = '/the_app/get-employee-name/' + employee_number;

Also, you don’t need ‘data’ in the ajax call parameters, since you’re expecting the employee_number from the url.

Finally, I would add:

console.log('data: %o', data)

to the success callback to make sure you’re receiving what you expect

Leave a comment