[Django]-How can I pass values/parameters from HTML to Django Views?

7👍

Understanding from the previous answer, if you do not want the search values to be sent as URL parameters, you can send them via an AJAX POST call and handle that in the view, like this:

<div>
    <input id="search" name="search" type="text" class="query-search" placeholder="Search...">
    <input onclick="setGetParameter()" type="button" class="btn btn-primary" value = "View Details"/>
</div>


<script>

function setGetParameter(){
    var search_word = $("#search").val();
    $.ajax({
      type: "POST",
      url: {% url 'view_detail' %},
      data: search_word,
      success: function(result){
        alert("Success");
      }
    });
}
</script>

Your view should look something like this.

def search_view(request):
    if request.method == "POST":
        search_word = request.POST['data']

URL configurations will remain the way other answers describe them.

7👍

You can create a HTML form and can submit the form using post method if you do not want to pass values in url.

<div>
<form action="{% url 'view_detail' %}" method="post">
{% csrf_token %}
<input id="search" name="search" type="text" class="query-search" 
 placeholder="Search...">
<input class="btn btn-primary" type="submit" value="submit">
</form>
</div>

And then in your view you can fetch the data as request.POST.get(‘search’):

def view_detail(request):
    searchWord = request.POST.get('search','')
    return HttpResponse(searchWord)

In the same way you can pass multiple parameters.

3👍

You can make a button works like a link in your templates, and add the js function on the onclick event, then get the search input value and add the search parameter to the url window.location.href:

<div>
    <input id="search" name="search" type="text" class="query-search" placeholder="Search...">
    <input onclick="setGetParameter()" type="button" class="btn btn-primary" value = "View Details"/>
</div>


<script>

function setGetParameter(){
    searchWord = document.getElementById('search').value;
    window.location.href = "{% url 'view_detail' %}" + "?search="+searchWord;
}
</script>

In the views, you can use request.GET.get('search') to get the parameters (search content) you input from the templates, like this:

def view_detail(request):
    searchWord = request.GET.get('search')
    return HttpResponse(searchWord)

BTW, the urlpatterns is look like this:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^view$', views.view_detail, name='view_detail'),
]
👤Tiny.D

Leave a comment