Not able to retrieve data values from Ajax GET call into Django view

Viewed 123

I am trying to query the employee list based on parameter I send through ajax call inside data, but it giving me an error (i want it through GET req only )

Js ajax func

  $(document).ready(function () {
    $(".call_ajax").click(function () {
      $.ajax({
        url: "/employee_list",
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        data: {
          designation: "soft eng",
        },
        headers: {
          "X-CSRFToken": csrftoken,
          Authorization: my_token,
        },
        success: function (data) {
          console.log(data);
        },
        error: function (xhr) {
          //Do Something to handle error
          console.log(xhr.error);
        },
      });
    });

my view

@csrf_exempt
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
@authentication_classes([TokenAuthentication])
def employee_list(request):

    if request.method == 'GET':
        data_ = request.data['designation']
        print(data_)
        employees = Employee.objects.all()
        students = Student.objects.all()
        user = MyUser.objects.all()
        serializer = EmployeeSerializer(employees, many=True)
        serialized_sudents = StudentSerializer(students, many=True)
        multi = {
            'employees': serializer.data,
            'students': serialized_sudents.data
        }
        # serializer2 = UserSerializer(user, many=True)
        return JsonResponse(multi, safe=False)

error i am getting in browser

GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error)

error in Django log

 File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list
    data_ = request.data['designation']
KeyError: 'designation'
2 Answers

request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES

You can use request.GET.get('designation')

@csrf_exempt
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
@authentication_classes([TokenAuthentication])
def employee_list(request):

    if request.method == 'GET':
        data_ = request.GET.get('designation') # Here I made changes
        print(data_)
        employees = Employee.objects.filter(designation=data_) # Map parsed data with database field
        students = Student.objects.all()
        user = MyUser.objects.all()
        serializer = EmployeeSerializer(employees, many=True)
        serialized_sudents = StudentSerializer(students, many=True)
        multi = {
            'employees': serializer.data,
            'students': serialized_sudents.data
        }
        # serializer2 = UserSerializer(user, many=True)
        return JsonResponse(multi, safe=False)

or

You can override get_queryset method. As for query string parameters request.data holds POST data, you can get query string params through request.query_params

def get_queryset(self):
    data = self.request.query_params.get('designation')
    queryset = Model.objects.filter() # use whatever you want filter
    return queryset

To know more about request.data and request.query_params, here is the link Request parsing link

It is most probably because you are using GET, but the data resides in body. Have a look at this. To try to fix this, change your request method to POST:

      $.ajax({
        url: "/employee_list",
        type: "POST",
        ...
Related