Home > Net >  Django Ajax POST request fail to redirect
Django Ajax POST request fail to redirect

Time:04-06

I am trying to create a website to capture picture from client's camera and save it in the database. However after everything was saved, I cant seem to redirect the page.

views.py

def facial_capture(request):
    if request.method == 'POST':
        file = request.FILES['snap']
        if file:
            student = Student.objects.get(id=request.session['id'])
            if student:
                FaceImage.objects.create(student=student, image=file)
                return HttpResponse("{'status': 1}", content_type='application/json')
        return HttpResponse("{'status': 0}", content_type='application/json')
    return render(request, 'id_capture/facial_capture.html')

face_capture.html

{% block body %}
    <div >
        <form>{% csrf_token %}
            <video id="video" width="640" height="480" autoplay></video>
            <button id="send">Submit</button>
            <canvas id="image_canvas" width="640" height="480"></canvas>
        </form>
    </div>
{% endblock %}

face_capture.js

$(document).ready(function () {
    var video = document.getElementById('video');
    var canvas = document.getElementById('image_canvas');
    var context = canvas.getContext('2d');
    var w = 640, h = 480;

    if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
            video.srcObject = stream;
            video.play();
        });
    }

    document.getElementById("send").addEventListener("click", function() {
        context.translate(w, 0);
        context.scale(-1, 1);
        context.drawImage(video, 0, 0, w, h);
        canvas.toBlob(upload, "image/jpeg");
    });

    function upload(file) {
        var formData =  new FormData();
        formData.append("snap", file);
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        $.ajax({
            headers: {'X-CSRFToken': csrftoken},
            type: 'POST',
            url: '/signup/facial_capture',
            data: formData,
            cache: false,
            processData: false,
            contentType: false,
            enctype: 'multipart/form-data',
            success: function(data){
                console.log('response received');
                if (data.status == 1) {
                    console.log('status ok');
                    window.location.href = "login";
                } else {
                    console.log('status failed');
                    window.location.reload();
                }
            }
        })
    }
});

I assume that after the return HttpResponse it will get to the function in ajax success and redirect to login page but somehow I am still at the facial_capture page with csrfmiddlewaretoken attached.

My question is that is this the right way to redirect the page after successfully send post request with ajax or am I doing anything wrong?

CodePudding user response:

First of all, instead of a HttpResponse you could use a JsonResponse that takes in a dictionary. Secondly, window.location.href takes either an absolute url or a relative url starting with a /

CodePudding user response:

//  Your django code should be like this

return HttpResponse(json.dumps({'status': "1"}), content_type="application/json")

And in the Django template, you should assign the url as follows. {% url 'login' %}

function upload(file) {
        var formData =  new FormData();
        formData.append("snap", file);
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        $.ajax({
            headers: {'X-CSRFToken': csrftoken},
            type: 'POST',
            url: '{% url 'facial_capture' %}',
            data: formData,
            cache: false,
            processData: false,
            contentType: false,
            enctype: 'multipart/form-data',
            success: function(data){
                console.log('response received');
                if (data.status == 1) {
                    console.log('status ok');
                    window.location.href = "{% url 'login' %}";
                } else {
                    console.log('status failed');
                    window.location.reload();
                }
            }
        })
    }
  • Related