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 views.py 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>
</div>

Below is my script function

<script>
    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
    }
</script>

Below is my views.py code

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

Answer

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 (views.py) In that example i will use ajax.

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

In your urls.py

    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>

<script>
 function send_value(){

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

              alert(response)
              }
              });
}
</script>

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

@csrf_exempt
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 *