[Solved]-How to execute file.py on HTML button press using Django?

14πŸ‘

βœ…

You want to try to submit a form on the button click. You can then import the functions you want to run from the script and call them in your view. You then redirect to the same page.

I hope this helps!

index.html

<form method="post">
    {% csrf_token %}
    <button type="submit" name="run_script">Run script</button>
</form>

views.py

if request.method == 'POST' and 'run_script' in request.POST:

    # import function to run
    from path_to_script import function_to_run
    
    # call function
    function_to_run() 

    # return user to required page
    return HttpResponseRedirect(reverse(app_name:view_name))
πŸ‘€James

4πŸ‘

Adding to answer above. You can run the function in a different view completely:

<form method="post" action="{% url 'app:view/function' %}">
{% csrf_token %}
<button class="btn btn-danger btn-block btn-round">Perform task</button>
</form>

And render whatever template you want (same template will execute task but seem like nothing has happened). This is handy if you already have a β€˜POST’ form handler.

πŸ‘€Josh

Leave a comment