Radio button not saving selected option when refreshed (Django)

Viewed 41

i have been having issues with my django ecommerce application

one part of my application the user is meant to check a radio button

the issue

  {% for option in deliveryoptions %}
    <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}"
                  value="{{option.id}}">
{% endfor %}

my ajax

    $('input[type=radio][name=deliveryOption]:checked').on('change', function (e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: '{% url "checkout:cart_update_delivery" %}',
      data: {
        deliveryoption: $(this).val(),
        csrfmiddlewaretoken: "{{csrf_token}}",
        action: "post",
      },
      success: function (json) {
        document.getElementById("total").innerHTML = json.total;
        document.getElementById("delivery_price").innerHTML = json.delivery_price;



      },
      error: function (xhr, errmsg, err) {},
    });

  });

my view

    def cart_update_delivery(request):
cart = Cart(request)
if request.POST.get("action") == "post":
    delivery_option = int(request.POST.get("deliveryoption"))
    delivery_type = DeliveryOptions.objects.get(id=delivery_option)
    updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price)

    session = request.session
    if "purchase" not in request.session:
        session["purchase"] = {
            "delivery_id": delivery_type.id,
        }
    else:
        session["purchase"]["delivery_id"] = delivery_type.id
        session.modified = True

    response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price})
    return response

once i check the radio button, everything works fine but once i refresh the page, the selected radio button disappears but the radio button value is still stored in session.

how do i fix it in such a way that even though i refresh the page, the selected radio button would still be selected.

0 Answers
Related