Reputation: 1125
using Django I want to create a website on which
And I also want a following condition:
In a simpler word, I want to button-click and the run python script in the server. I've created the button-and-call-function script as follows, but it causes error because returned value is 1 and not rendering function.
How can I achieve the goal?
app_name/templates/app_name/index.html
<body>
<form action='some_function' method='GET'>
<button type='submit'>Click Here</button>
</form>
</body>
app_name/views.py
def some_function(request):
print("do something here")
return 1 # error is caused here but I don't want re-render
app_name/url.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.show_view, name='view'),
path('do_something', views.do_something, name='do_something')
]
Thanks!
Upvotes: 0
Views: 5709
Reputation: 870
You can use AJAX to run python functions asynchronously. If you want to run your python script when a button is clicked use the "onclick" event listener to call your AJAX function.
Use the URL you defined in your urls.py file and the view will get called asynchronously.
Your HTML
<body>
<input type='button' value='run function' onclick='runScript()'>
</body>
Javascript with JQuery will provide us with an easy way to make the AJAX call
function runScript() {
$.ajax({
url: 'do_something', //The URL you defined in urls.py
success: function(data) {
//If you wish you can do additional data manipulation here.
}
});
}
views.py
from django.http import HttpResponse
def some_function(request):
#Code to run
#More code to run
return HttpResponse('Return data to ajax call')
If I understood correctly you want to run python code when a button is clicked and the form's data is irrelevant.
If you are looking to actually use the form data then you may need to use e.preventDefault() in your ajax call to prevent the form from submitting and then send the data via your AJAX function.
Upvotes: 5