Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How can I call a view function from template?

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.

like image 665
Robert Avatar asked Jul 11 '13 16:07

Robert


People also ask

Can I call a function in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

How do you call a function from a view?

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.

How do you call a function within a function in Django?

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.


2 Answers

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') 
like image 51
Mahshid Zeinaly Avatar answered Oct 02 '22 20:10

Mahshid Zeinaly


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) }          });      }); }); 
like image 20
karthikr Avatar answered Oct 02 '22 21:10

karthikr