skip to Main Content

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 class="container">
        <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?

Edit:
url.py

urlpatterns = [
    path('login', views.login, name='login'),
    path('signup/facial_capture', views.facial_capture, name='facial_capture')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

3

Answers


  1. Chosen as BEST ANSWER

    I have managed to figure out why. I forgot to declare button type, and by default it is a submit button. All I need to do is to change the button to:

    <button id="send" type="button">Submit</button>
    

    And also, by everyone suggestion, I should change the response to:

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

  2. 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 /

    Login or Signup to reply.
  3. //  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);
            formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
            $.ajax({
                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();
                    }
                }
            })
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search