I have a question on how to call a view function from a template HTML button? Like an onclick function? Here is the template:
<input id="submit" type="button" onclick="xxx" method="post" value="Click" />
And the views.py is:
def request_page(request): ...do something... return render_to_response("/directory.html", {})
Thank you very much.
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
To call a view function from template with Python Django, we can add a link to the URL of the view function. to add a link to the view with name delete_product in admin_page. html. to add the path to the delete_product view.
You have two paths to go down: Have func2 return an HttpResponse object (And pass it the request argument as well) and then have func1 return what func2 returned (an HttpResponse object). Have func2 return whatever it is you want, and have func1 return an HTTPResponse object.
Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.
inside templateHTML.html:
<form action="#" method="get"> <input type="text" value="8" name="mytextbox" size="1"/> <input type="submit" class="btn" value="Click" name="mybtn"> </form>
inside view.py:
import mypythoncode def request_page(request): if(request.GET.get('mybtn')): mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) ) return render(request,'myApp/templateHTML.html')
One option is, you can wrap the submit
button with a form
Something like this:
<form action="{% url path.to.request_page %}" method="POST"> <input id="submit" type="button" value="Click" /> </form>
(remove the onclick
and method
)
If you want to load a specific part of the page, without page reload - you can do
<input id="submit" type="button" value="Click" data_url/>
and on a submit
listener
$(function(){ $('form').on('submit', function(e){ e.preventDefault(); $.ajax({ url: $(this).attr('action'), method: $(this).attr('method'), success: function(data){ $('#target').html(data) } }); }); });
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