1

I am trying to retrieve the value of the selected item from a dropdown list at CreateView using Ajax call. For example, when an item has been selected from the dropdown menu, I want all of the related information of that item to be automatically displayed on the template.

But I am not sure why I won't be able to return the value of the selected item (which will be needed for filtering) at CreateView with the following codes:

models.py

class Model_Item(models.Model):
    item_name = models.CharField(max_length = 20)
    item_description = models.CharField(max_length = 100)
    item_origin = models.CharField(max_length = 50)
    # and many more fields

    def __unicode__(self):
        return self.item_name

class Model_Cart(models.Model):
    item = models.ForeignKey(Model_Item)
    customer_name = models.CharField(max_length = 50)

html

<form method = "POST"> {% csrf_token %}
    <table id = "table_01">
        <tr>
            <th>Item name</th>
            <td>{{ form.item}}</td>
        </tr>
    </table>
    <div>
        preview the description, origin and other fields of the choosen item here -->
    </div>
    <table id = "table_02">
        <tr>
            <th>Customer's name</th>
            <td>{{ form.customer_name}}</td>
        </tr>
    </table>
    <input type = "submit" value = "Submit">
</form>

ajax

$(document).ready(function(){
    $("#id_item").change(function(){
        var item_selection = $(this).val();
        $.ajax({
            type: "GET",
            data: {"item_name_id": item_selection}
        });
    });
});

views.py

class View_Cart(CreateView):
    form_class = Form_Cart

    def get_queryset(self):
        item_name_id = self.request.GET.get("item_name_id")
        print item_name_id # <------ Does not print anything

I have referred to this link but to no avail. This source says that we can't use "get_queryset" on CreateView, but here it says that "get_queryset" is one of the available functions on CreateView.

Does anyone have the solution to this?

Fxs7576
  • 1,259
  • 4
  • 23
  • 31

0 Answers0