fetch api GET method with Django

Asked

Viewed 312 times

0

Talk guys good day, I’m with a form that the user enters Cpf and ra and receives its id_registration, I’m trying to do this with ajax, but always returns 500 Internal Server Error, follows my line of code:

Recovery-id.js:

const recoveryButtom = document.querySelector('#recovery-id');
const inputs = document.querySelectorAll('input');
recoveryButtom.onclick = recoveryID;

function recoveryID() {
    
    let csrfToken;
    for (let input of inputs) {
        if (input.name === 'csrfmiddlewaretoken') {
            csrfToken = input.value;
        }
    }
    
    fetch('/recuperar-id', {
        headers:{
        'Content-type': 'application/json',
        'X-CSRFToken': csrfToken
        },
    })
        .then(function(sucess){
            console.log(sucess);
        })
        .catch(function(error){
            console.log(error);
        });
}

py views.:

def get_id(request):

    form = StudentForm(request.GET or None)
    if form.is_valid():
        data = form.cleaned_data
        student = Student.objects.filter(cpf=data['cpf']).filter(ra=data['ra']).first()

        if not student:
            return JsonResponse({'studentNotFound': 'O aluno não encontrado'}, status=400)
        
        return render(request, 'index.html', {'student':student})

    return JsonResponse({'student':student})

if anyone can help me I will be very grateful, thanks guys!!!

  • If it returns error 500, it means that there is an error in this function, which the debug of Django shows about?

1 answer

1

In your code there are some things that are not consistent:

  • In Javascript you are taking the values of your input but do not transmit your data to the URL or to the body of the request. For example: fetch('/recuperar-id/' + csrftoken). You just set a few request headers. Remember to adjust the URL in the.py urls if necessary.
  • Since you are not passing any information in Javascript, Django cannot receive anything and the form will never be valid since request.GET has no data Pick up.
  • Since the form is not valid, the execution jumps to that line: return JsonResponse({'student':student}) and notice that the variable 'student' is not declared for this scope and that is probably what causes this error.

What I advise you to do:

  1. Please review your Javascript to send the data correctly to the Back-end
  2. With Javascript working, get the information right, work with the form and execute your logic

Note: Put this last Return of your code that causes errors in an 'I' so you can do this: return JsonResponse({'student': ''}) or some other format your application should accept and so avoid breaking the execution

  • really were missing some things, I decided to send the data via POST and receive the Id_registration in Sponse, it took a while but I managed to solve the problem, I will put here the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.