Erickson Kitoz
Erickson Kitoz

Reputation: 53

Django forms: how to get product's data from db with ajax

I have models (ShopStock and SaleItem), I have registered product and price in ShopStock model, in SaleItem model i also have product and price fields. What i want is when i select a product in (SaleItemForm) the price field to be filled with a price from Shopstock model. I have no idea how to do it in javascript.

Models

class Product(models.Model):
    name = models.CharField(max_length = 100, blank=True)


class ShopStock(models.Model):
    products = models.ForeignKey(Product, null=True, blank=True, on_delete = models.SET_NULL)
    price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)


class SaleItem(models.Model):
    product = models.ForeignKey(ShopStock, null=True, blank=True, on_delete = models.SET_NULL)
    quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
    price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)

I tried this to solve my problem but it's not working

Views

def price(request):
    if request.method == 'GET':
        total_price = SaleItem.price
        response_data ={}
        response_data['price'] = total_price

    return JsonResponse(response_data)

Templates

  $(document).ready(function() {
  $('#id_product').change(function(){
      var query = $(this).val();
      console.log(query);
      $.ajax({
          url : "/price/",
          type : "GET",
          dataType: "json",
          data : {
              client_response : query
              },
          success: function(json) {
              document.getElementById('id_price').value=json.price;
          },
          failure: function(json) {
              alert('Got an error dude');
          }
      });
  });
});

Forms

class SaleItemForm(forms.ModelForm):

    product = forms.ModelChoiceField(queryset=ShopStock.objects.all(), widget=forms.Select(attrs={'class':'form-control', 'id':'id_product'}))

    class Meta:
        model = SaleItem
        fields = ['product', 'quantity', 'price']

        widgets = {

        'quantity': forms.NumberInput(attrs={'class': 'form-control'}),
        'price': forms.NumberInput(attrs={'class': 'form-control', 'id':'id_price'})

        }

Urls

url(r'^price/$', views.price, name='price')

Any help or idea will be appreciated.

Upvotes: 1

Views: 741

Answers (1)

Mehmet Can
Mehmet Can

Reputation: 116

The problem lies in total_price = SaleItem.price . Price of which SaleItem instance? You need to filter and get special model instance.

You already pass a data from ajax function to views by data :{client_response : query}. So, you can use this to filter .

def price(request):
    if request.method == 'GET':
        selectedProduct = request.GET['client_response']
        total_price = SaleItem.objects.filter(product = selectedProduct).first().price
        response_data ={}
        response_data['price'] = total_price

        return JsonResponse(response_data)

Upvotes: 1

Related Questions