Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
Django how to make a button that first runs js function and then function in .py

I am building a Django app and on one of my HTML sheets, I have a button that should first run a js function(ocr()) and then another function in the .py.

I've tried the first solution to this post. And now it runs the javascript function but it doesn't go on to the function in the .py.

UPDATE: I added the onsubmit event and the function returns true now. But it still doesn't work.

This is the js script:

<div>
        
        <script>
            var ocr = function(event){
                event.preventDefault();

                Tesseract.recognize(
                    document.getElementById('imgde').src,
                    'deu',
                    { logger: m => console.log(m) }
                ).then(({ data: {text}}) => {
                    console.log(text);
                    document.getElementById('txt_voc_de').innerHTML = ['<input type="hidden" name="txt_voc_de" id="txt_voc_de" value="',text, '"/>'].join('');
                })

                Tesseract.recognize(
                    document.getElementById('imgen').src,
                    'eng',
                    { logger: m => console.log(m) }
                ).then(({ data: {text}}) => {
                    console.log(text);
                    document.getElementById('txt_voc_en').innerHTML = ['<input type="hidden" name="txt_voc_en" id="txt_voc_en" value="',text, '"/>'].join('');
                })
                
                
   
                
            };

            var form = document.getElementById("imgForm");
            form.addEventListener("submit", ocr, true);
        </script>
        <input type="submit" onsubmit="ocr();" id="senden" class="inputfiles" />
        <button for="senden" class="button" id="weiter_btn" >WEITER</button>
        {% csrf_token %}
        </div>

UPDATE 2:

I am now trying to send a request to a URL in the JS function and have it be picked up by a view. But it only returns the previous html sheet.

This is the updated script:

<div>
        
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
            $(document).ready(function () {
                $("#imgForm").submit(function (event) {
                    event.preventDefault();
                    $.ajax({
                    type: "POST",
                    beforeSend: function() {
                        Tesseract.recognize(
                            document.getElementById('imgde').src,
                            'deu',
                            { logger: m => console.log(m) }
                        ).then(({ data: {text}}) => {
                            console.log(text);
                            document.getElementById('txt_voc_de').innerHTML = ['<input type="hidden" name="txt_voc_de" id="txt_voc_de" value="',text, '"/>'].join('');
                        })

                        Tesseract.recognize(
                            document.getElementById('imgen').src,
                            'eng',
                            { logger: m => console.log(m) }
                        ).then(({ data: {text}}) => {
                            console.log(text);
                            document.getElementById('txt_voc_en').innerHTML = ['<input type="hidden" name="txt_voc_en" id="txt_voc_en" value="',text, '"/>'].join('');
                        })
                    } ,
                    url: "/upload/",
                    success: function () {
                        $('#message').html("<h2>Contact Form Submitted!</h2>")
                    }
                    });
                    return false;
                });
                });
            
        </script>
       <input type="submit" id="senden" class="inputfiles"/>
       <button for="senden" class="button" id="weiter_btn" >WEITER</button>
        {% csrf_token %}
        </div>

The problem probably is that the beforesend function is in javascript right? But is there a way I can run that function in javascript before the ajax request?

And this is my function in views.py

def upload(request):
    if request.is_ajax():
        message = "Yes"
        txt_voc_en = request.POST.get("txt_voc_en")
        txt_voc_de = request.POST.get("txt_voc_de")
        print(txt_voc_de)
        print(txt_voc_en)

        vocsde = ocr_core(txt_voc_de)
        vocsen = ocr_core(txt_voc_en)
        
        messages.success(request, vocsde, extra_tags="de")
        messages.success(request, vocsen, extra_tags="en")
        context = {'vocsen': vocsen,
                    'vocsde': vocsde}
        return render(request, 'success.html', context)
     else:
        message = "Not ajax"
     return HttpResponse(message)



over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

As per your question, you first want to process some form data via JavaScript, embedding the results in hidden input types. Finally you want to send those hidden input's data to views.py for further process. In the updated script, you mixed javascript with AJAX. You can update you script as followed -

<script>
    var ocr = function(event) {
        event.preventDefault();

        Tesseract.recognize(
            document.getElementById('imgde').src,
            'deu', {
                logger: m => console.log(m)
            }
        ).then(({
            data: {
                text
            }
        }) => {
            console.log(text);
            Tesseract2(text);
        })
    };

function Tesseract2(text_de) {
    Tesseract.recognize(
        document.getElementById('imgen').src,
        'eng', {
            logger: m => console.log(m)
        }
    ).then(({
        data: {
            text
        }
    }) => {
        console.log(text);
        AjaxCall(text_de, text);
    })

}

function AjaxCall(text_de, text_en) {
    $.ajax({
        type: 'POST',
        url: "/upload/",
        data: {
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), // to avois csrf error
            txt_voc_en: text_en,
            txt_voc_de: text_de
        },
        success: function(json) {
            //Do whatever you want
        },
        error: function(xhr, errmsg, err) {
            console.log(xhr.status + ": " + xhr.responseText);
        }
    });
}

var form = document.getElementById("imgForm");
form.addEventListener("submit", ocr, true);
</script>

This code will first do preprocessing via javascript and then send it to views.py via AJAX with required parameters "txt_voc_en" and "txt_voc_de".

over 4 years ago · Santiago Trujillo Denunciar

0

You could send a request to a URL in the JS function and have it be picked up by a view.

This post should help you

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda