Maddie Graham
Maddie Graham

Reputation: 2177

Transferring multiple values from template to views in Django

I am working on a simple game where the user can select many numbers in the template and then I would like to pass them on to the views.

My template looks like this:

enter image description here

  <div class="col-lg-2">
    <div class="card text-center bg-gradient-primary border-0 hover-shadow-lg hover-translate-y-n3 mb-4 ml-lg-0">
      <div class="card-body">
        <div class="d-inline-flex align-items-start">
          <div class="pl-0">
            <span class="d-block h2 text-white mr-2 mb-1"><b>1</b></span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-2">
    <div class="card text-center bg-gradient-primary border-0 hover-shadow-lg hover-translate-y-n3 mb-4 ml-lg-0">
      <div class="card-body">
        <div class="d-inline-flex align-items-start">
          <div class="pl-0">
            <span class="d-block h2 text-white mr-2 mb-1"><b>2</b></span>
          </div>
        </div>
      </div>
    </div>
  </div>

Now the user selects the field 9, 13, 16, 19, 22. I would like to pass all the values ​​at once after click button "Choices number". Without refreshing the page (until the button is clicked). How can I do this? I was thinking about using a hidden field <input type="hidden" name="number1" value="1"> but it would refresh every time my template.

One option would be to pass the value using method get, setting something like that for each card element href=?button_number_1=1 and then, get them in the view using request.GET['button_number_1']. And avter this save all using method post. But maybe there is another way to do it?

Upvotes: 1

Views: 402

Answers (1)

Mukul Kumar
Mukul Kumar

Reputation: 2103

urls.py

path(r'ajax/your_function_name/', your_function_name, name='your_function_name'),


html file

# You need to use ajax call

$('.text-white').on('click', function () {
        $.ajax({
            type : "POST",
            url: '/ajax/your_function_name/',
            data : $(".text-white").text(),
            success: function (data) {
        # after success function return value, perform your action
            }
        });
});


views.py

def your_function_name(request):
    print(request.data)
    pass

Upvotes: 1

Related Questions