Reputation: 85
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?
Upvotes: 0
Views: 1631
Reputation: 568
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')
Upvotes: 2