0

I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page.

For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number".

I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered.

I get this error when trying to see the page now, I'm not sure where I'm passing the "id/employee_number" incorrectly which is causing this to show:

NoReverseMatch at /operations/enter-exit-area/
Reverse for 'ajax_get_employee_name' with keyword arguments '{'id': 'employee_number'}' not found. 1 pattern(s) tried: ['operations/get\\-employee\\-name\\/(?P<id>[0-9]+)\\/$']

models.py

class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
    employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
    work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False)
    station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True,  blank=True)

    def __str__(self):
        return self.employee_number

This is the model where the name is stored

alldata/models.py

class Salesman(models.Model):
    slsmn_name = models.CharField(max_length=25)
    id = models.IntegerField(db_column='number', primary_key=True)

I was reading I can add to the "attrs" in the widget an 'onchange' part, but I am not too familiar with how to approach this and tying it to the ajax request from forms and not the html.

forms.py

class WarehouseForm(AppsModelForm):
    class Meta:
        model = EmployeeWorkAreaLog
        widgets = {
            'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
        }
        fields = ('employee_number', 'work_area', 'station_number')

views.py

class EnterExitArea(CreateView):
    model = EmployeeWorkAreaLog
    template_name = "operations/enter_exit_area.html"
    form_class = WarehouseForm

    def form_valid(self, form):
        # do submission stuff..


def get_employee_name(request):
    employee_number = request.GET.get('employee_number')
    employee = Salesman.objects.get(id=employee_number)
    employee_name = employee.slsmn_name
    return employee_name

urls.py

urlpatterns = [
    url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),

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

The ajax request I tried to create is at the end of this html. I modified a similar request I found, but it does not actually display anything on the screen, not sure if I'm missing an area where the request is actually never being called, as I am not too familiar with how these types of requests work.

enter_exit_area.html

{% extends "base.html" %}

{% block main %}
    <form id="warehouseForm" action="" method="POST" novalidate >
        {% csrf_token %}
        <div>
            <h1 get-employee-name-url="{% url 'operations:ajax_get_employee_name' id='employee_number' %}"></h1>
            <div>
                {{ form.employee_number.help_text }}
                {{ form.employee_number }}
            </div>
            <div>
                {{ form.work_area.help_text }}
                {{ form.work_area }}
            </div>
        </div>

        <div>
            <div>
                <button type="submit" name="enter_area" value="Enter">Enter Area</button>
            </div>
        </div>
    </form>

    <script>
        $("#id_employee_number").change(function () {
            var employee_number = $(this).val();
            var url = $("#warehouseForm").attr("get-employee-name-url");

            $.ajax({
                url: url,
                type:'GET',
                data: {
                    'id': employee_number
                },
                success: function (data) {
                    var employee_name = data;
                    $('#employee_name')[0].innerHTML = employee_name;
                }
            });
        });
    </script>

1 Answers1

0

There are two issues with your code:

1. You are not reversing you URL correctly.

The reason your code is throwing this exception, is in the following line:

<h1 get-employee-name-url="{% url 'operations:ajax_get_employee_name' id='employee_number' %}"></h1>

First of all, the url does require a keyword argument id, but it should be an int. Right now you are passing the literal value 'employee_number' instead of (for example) form.employee_number.

However, even if you were to pass a valid variable, this would still not work.

The template tag {% url %} is evaluated on the server side, so the url is constructed when the page is sent from the Django server, while everything inside the <script> tags is executed on the user's browser. Constructing a url containing an ID on the server side is not what you want, because the url will then always be something like /get-employee-name/20/.

Since you're already passing the employeeID through the GET parameters, the best way to solve this is by changing the url not to take a parameter:

path('get-employee-name/', views.get_employee_name, name='ajax_get_employee_name')

2. get_employee_name does not return a valid response.

From the docs:

A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response.

Right now, you are returning a plain string. Wrapping the string in a JSON response should work. Also, while a single string might not cause any issues, I like to wrap my response in a dictionary. This will also allow you to return some error value when the request is not valid, or when no employee is found for that ID.

def get_employee_name(request):
    employee_number = request.GET.get('employee_number')

    try:
         employee = Salesman.objects.get(id=employee_number)
    except Salesman.DoesNotExist:
        return JsonResponse({'error': 'Employee not found'}, status=404)

    employee_name = employee.slsmn_name
    return JsonResponse({'employee_name': employee_name})

Make sure to correctly get the data from the response (And handle errors correctly):

  $.ajax({
            url: url,
            type:'GET',
            data: {
                'id': employee_number
            },
            success: function (data) {
                var employee_name = data['employee_name';
                $('#employee_name')[0].innerHTML = employee_name;
            }
            error : function (data) {
                var error_message = data['error]';
                $('#employee_name')[0].innerHTML = error_message;
            }
        });
Nico Griffioen
  • 5,143
  • 2
  • 27
  • 36