Calling FUNC from JS

Hi I installed the tax code calculation app.
I inserted the function in the POST function and when it saves it performs the calculation and stores the Tax Code.
I would like to make it work like this, to the right of the field insert a button and on its click perform the calculation with its result display.
I think it should be done with js but I didn’t understand how to call the function from JS
Or is there any other method ?
I post the code of the view

class AssociatiInseView(View):
    template_name = 'Pale/Tabelle/AssociatiInse.html'

    def get(self, request):
        form = AssociatiForm()
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = AssociatiForm(request.POST)

        if form.is_valid():
            associato = form.save(commit=False)
            # # comune.Anagrafica = request.Anagrafica
            # cognome = form.cleaned_data.get('Cognome', '')
            # nome = form.cleaned_data.get('Nome', '')
            # associato.Anagrafica = cognome + ' ' + nome

            # Calcolo del C.F.
            lastname = form.cleaned_data.get('Cognome')
            firstname = form.cleaned_data.get('Nome')
            gender = form.cleaned_data.get('Sesso')
            birthdate = form.cleaned_data.get('DataNascita')
            # Conversione della Data in Stringa
            birthdate_str = birthdate.strftime('%d/%m/%Y')
            # birthdate_str = form.cleaned_data.get('DataNascita')[0].strftime('%d/%m/%Y') if isinstance(
            #     form.cleaned_data.get('DataNascita'), tuple) else form.cleaned_data.get('DataNascita').strftime(
            #     '%d/%m/%Y')

            birthplace = form.cleaned_data.get('ComuneNascitaID').Comune
            print(' birth ', birthdate, birthdate_str)
            associato.CodFiscale = codicefiscale.encode(
                lastname = lastname,
                firstname = firstname,
                gender = gender,
                birthdate = birthdate_str,
                birthplace = birthplace,
            )
            # print('c.f. ', associato.CodFiscale)

            # Quando non viene inserita la foto, memorizza il link al file di Base
            if 'Foto' in request.FILES:
                associato.Foto = request.FILES['Foto']
            else:
                # Se nessuna nuova immagine è stata fornita, mantieni il valore predefinito
                associato.Foto = 'Sito/Mamozio.png'
            associato.save()
            # Aggiungi un messaggio di successo
            messages.success(request, f"ANAGRAFICA '{associato.Anagrafica}' - SALVATA ")
            # Azzerare i campi del form
            form = AssociatiForm()
        else:
            # Stampa tutti gli errori dei campi del form nel terminale
            for field, errors in form.errors.items():
                messages.error(request, f"Errore nel campo {field}: {', '.join(errors)}")
                print(f"Errore nel campo {field}: {', '.join(errors)}")
                print("Errore nel form.")
                # return HttpResponseBadRequest("Errore nel form. .")

        # Redirect alla stessa pagina
        return redirect(reverse('AssociatiInse'))

Your interface from the browser to the server is either through http requests or websockets. JavaScript doesn’t have any way to directly call a function on the server.

Your JavaScript code can issue an http GET or POST to send a request to a url.

Django will route that request to a view.

The view will return a response.

The JavaScript can do whatever it wants to do with that response.

Based on what you have indicated to me I have provided in this way, tell me if the reasoning and the sequence is right

<button type="button" id="CF" class="btn btn-success" onclick="calcolaCF()" formmethod="POST"> Calcolo C. F.! </button>

JS
    function calcolaCF() {
console.log('CF ')
        var cognome = document.getElementById('id_Cognome').value;
        var nome = document.getElementById('id_Nome').value;
        var sesso = document.getElementById('id_Sesso').value;
        var dataNascita = document.getElementById('id_DataNascita').value;
        var comuneNascita = document.getElementById('id_ComuneNascitaID').value;
        var cf = document.getElementById('id_CodFiscale').value;

console.log('Cognome ', cognome, comuneNascita, '/Tabelle/calcolaCF/'+ cognome +'/' nome )
//                fetch('/Tabelle/calcolaCF/'+ cognome +'/'+ nome)
                    .then(response => response.json())
                    .then(data => {
console.log('Cognome AAAAAAAAAAAAAAAAAAAA' )
                    })    /// FINE  .then.data */

                   .catch(error => console.error('Errore durante la richiesta:', error));

                cf.value = '????';
                console.log('CALC ', cf.value )

console.log('CF FINE')
      return ;
    }   /// FINE FUNC


PATH
path('Tabelle/calcolaCF/<str:cogn>/<str:nome>/', calcolaCF, name='calcolaCF'),

I haven’t figured out how to get the C.F. to display in the form field

Unfortunately, I’m probably not going to be able to help you here. I’m not familiar with using raw JavaScript fetch API for AJAX requests - I either use jQuery or HTMX.

There is one thing I can point out.

You have a trailing slash in your URL definition, which means you want to ensure you have a trailing slash in the url being requested:

That’s right, thank you