0

I'm trying to make an HTML button where you can call a Python function:

HTML

<script>
function login(){
  $.ajax({
    url: "/python_file",
    context: document.body
  }).done(function() {
  alert('finished python script');;
  });
}
</script>

<input id="clickMe" type="button" value="clickme" onclick="login();" />

urls.py

urlpatterns = [
    path('', views.home, name="index"),
    path('python_file', views.python_file),
]

views.py

from django.shortcuts import render

def home(request):
    return render(request, "login/login.html")

def python_file(email, password):
    pass

But, how can I pass an argument into the function?

2
  • Where is the argument supposed to be coming from? Commented Jan 9, 2021 at 10:02
  • the javascript action, so I want it to get values from a form, and then activate a function with values Commented Jan 9, 2021 at 10:15

1 Answer 1

2

Data is passed to the view as either a "POST" or a "GET" request.

Your ajax script sending data as a get request. - email & password are fictional, you'd have to get them from the form elements

<script>
function login(){
  $.ajax({
    url: "/python_file",
    type: "GET",
        data: {
        Email: email,
        Password: password,
    },

  }).done(function() {
  alert('finished python script');;
  });
}
</script>


<input id="clickMe" type="button" value="clickme" onclick="login();" />

Python file view function

def python_file(request):
    # if your ajax request is a GET use the following
    email = request.GET.get('email')
    password = request.GET.get('Password')

    # if your ajax request is a POST use the following
    email = request.POST.get('email')
    password = request.POST.get('password')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.