Perhaps there is a different way of going about this problem, but I am fairly new to using Django.
I have written a custom Python script and would like to run a function or .py file when a user presses a "submit" button on the webpage.
How can I get a parameter to be passed into a Python function from a submit button using Django?
If you also want to maintain your script separate from the view, you can also use a custom management command and use call_command to call it in the view. This way you can run the script from the command line as well with manage.py mycommand [myargument] . Save this answer.
Using the python Command To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!
Typically what is done is you'd have your form submit a post request. You'd then intercept the request in your urls.py, where you'd call your function. So if your form looks like this:
<form action="submit" method="post">
<input type="text" name="info"><br>
<input type="submit" value="Submit">
</form>
your urls.py would have something like this:
url(r'^submit', views.submit)
and your views.py would have the function that would get the parameters that were passed through the post:
def submit(request):
info=request.POST['info']
# do something with info
This link gives a more in depth explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With