Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python script in Django from submit

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?

like image 771
Matt Avatar asked Apr 30 '15 20:04

Matt


People also ask

How do you call a Python script in 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.

How do I run a .py file?

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!


1 Answers

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.

like image 80
neatnick Avatar answered Sep 18 '22 11:09

neatnick