[Fixed]-Show price based on product selected in form box

1👍

Nope!

This will cause so many requests to the server for only showing product price!

Best practice to always minimize requests as much as could to imporve website performance.

Now answering your question in regards fetching price:

In your html, in products for loop, add special tag to present product price in options..

For example:

         {% for item in products %}
          <select class="products">
                <option price="{{ item.price }}">
                      {{ item.name }}
                </option>
           </select>
          {% endfor %}

Now last step is to render product price according to selection with Javascript!

    $(document).on("change", '.products', function (event) {
           event.preventDefault();
           $('#id_price').val($(this).children(":selected").attr("price"));
    });

Before doing any ajax/request to the server, always think if this can be done in free SQL queries method.

0👍

Try this to disable a form field.

form = SaleForm()
form.fields['price'].widget.attrs['disabled'] = True

This just disable it in front end only. You have to o validations in backend form validation because, in frontend anyone can do disable to enable.

0👍

You should write javascript code to detect the onchange event of the product field. In the onchange event handler, you should fire the AJAX call to the backend to fetch the information for the selected product by passing the product_id. Typically, this is an another view function called from urls.py. Once the backend responds, the callback of AJAX call should update the price field. You can consider using jQuery instead of plain javascript to ease the implementation.

Leave a comment