Passing HTML input tag value to Django view

I have an input element in my django template which has an onclick event written in javascript I want the updated value of this input element to pass to my view in How to achieve this?

Below is my HTML element

<input id="minus" type="button" class="btn btn-black btn-outline-white py-3 px-4" size="5" value="-">
<input id="theInput" type="number" name="quantity" size="2" class="btn btn-primary btn-outline-black py-3 px-1" title="Qty" value="1" min="0" step="1">
<input id="plus" type="button" class="btn btn-black btn-outline-white  py-3 px-4" size="5" value="+">

<div class="py-1 bg-black ">
  <div class="row no-gutters slider-text align-items-end justify-content-center">
            <h4><a class="text"  type="button" onclick="send_value()" href="{% url 'mycart' %}/?item={{name}}&price={{price}}">Add To Cart</a></h4>

Below is my script function

    input = document.getElementById('theInput');
    document.getElementById('plus').onclick = function(){
      input.value = parseInt(input.value, 10) +1
    document.getElementById('minus').onclick = function(){
      input.value = parseInt(input.value, 10) -1

Below is my code

def mycart(request):
  quantity = request.POST.get('quantity')
  item = request.GET.get('item')
  return render(request, 'mycart.html', {'quantity': quantity,'item':item})


Let say that you want to pass to your django view the value of #theInput field : You need to use something that will handle the value of the input and send it the server ( In that example i will use ajax.

First you need a url that will refer the ajax request to the right view.

In your

    path('target_view/', views.YourView)

Now you need to send the value to the server using ajax, you need also a button or a link to trigger the ajax post action like bellow :

<button onclick='send_value()'> Submit input value </button>

 function send_value(){

             url: '/target_view/',
             method : 'POST',
             data: {quantity: $('#theInput').val()},
             beforeSend: function() {
              // things to do before submit
             success: function(response) {


And than you interpret the value in your view like this :

def GetInputValue(request):
  input_value = request.POST['quantity']
  return HttpResponse(input_value)

the csrf_exempt decorator is obligatory if you want to send data to server from input fields without the {% csrf_token %} on a form

Leave a Reply

Your email address will not be published. Required fields are marked *