fetch api GET method with Django

0
I'm trying to do this with ajax, but it always returns form , it follows my line of code:

/ p>

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);
        });
}

views.py:

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!

    
asked by anonymous 03.12.2018 / 14:10

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 body of the request. For example: fetch('/recuperar-id/' + csrftoken) . You just set some request headers. Remember to adjust the URL in urls.py if necessary.
  • Since you are not passing any information in Javascript, DJango can not receive anything and the form will never be valid since request.GET does not have any Paste data.
  • Since the form is not valid, execution skips to this line: return JsonResponse({'student':student}) and notice that the variable 'student' is not declared for this scope and is probably what causes this error.

What I advise you to do:

  • Please review your Javascript to send data back to Back-end
  • With JavaScript working, take the information right, work with the form and execute your logic
  • Note: Place this last return of your code that causes the errors in an 'else' to be able to do this: return JsonResponse({'student': ''}) or some other format that your application should accept and thus avoid breaking the execution

        
    05.12.2018 / 05:46