In a Django application, the AJAX request does not show any content when

When using a for loop inside my ajax request with Django inlineformset, the goal is to return the price when an admin selects an item. However, this functionality is not working correctly within the for loop.

class Item(models.Model):
     items = models.CharField(max_length=50)
     price = models.DecimalField(max_digits=10, decimal_places=3) # I need to retrieve this price
     def __str__(self):
        return self.items 

class Invoice(models.Model):
     admin = models.ForeignKey(User, on_delete=models.CASCADE)
     customer = models.CharField(max_length=50)
     items = models.ManyToManyField(Item, through='ItemsInvoice')

class ItemsInvoice(models.Model):
     invoice_no = models.ForeignKey(Invoice, on_delete=models.CASCADE)
     item = models.ForeignKey(Item, on_delete=models.CASCADE)
     quantity = models.IntegerField()
     price = models.DecimalField(max_digits=10, decimal_places=3) # When selecting an item, the price should be returned and populated in the price field

Here's a snippet of my views.py:

@login_required
def check_price(request):
   item = request.GET.get('invoice-0-item', None)
   price = Item.objects.get(id=item).price
   data = {
      'price': price,
   }
   return JsonResponse(data)

I'm struggling with iterating through the number of forms to achieve this:

@login_required
def check_price(request):
   for i in range(length of forms):
       item = request.GET.get('invoice-' + str(i) + '-item', None)
       # etc...

Lastly, I have to assign the returned price to the price field, but it fails within the for loop. Is there any way to accomplish this?

Updated: forms.py

class InvoiceItemForm(forms.ModelForm):
    item = forms.ModelChoiceField(
    queryset=Item.objects.all(), empty_label='---', widget=forms.Select(attrs={'onchange':'sellingPrice()'}))
class Meta:
    model = ItemsInvoice
    fields = [
        'item', 'quantity', 'price'
    ]

class CustomerInvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice
        fields = [
            'customer'
        ]

CustomerInvoiceInlineFormset = inlineformset_factory(
    Invoice, ItemsInvoice, form=InvoiceItemForm,
    fields=('item', 'quantity', 'price'), extra=1
)  

Answer №1

After careful consideration, your question has been clarified. It is recommended to utilize the jQuery change event for handling the select tag in your script.

To implement this change, update your script as follows:

$('.inp select.item').change(function() {
    let elm = $(this);

    $.ajax({
        url:'/ajax/price_validate/',
        data:{
            // elm.attr("name"): elm.val()
            // Alternatively,
            "item_id": elm.val()
        },
        success:function(data){
            if (data.price){
                elm.closest("div.inp").find("input.price").val(data.price);
            }
            else{
                alert('Price information is not available')
            }
        }
    })
})

In your views.py file:

@login_required
def check_price(request):
    query = request.GET
    data = {
        'price': Item.objects.get(id=query.get("item_id")).price,
    }
   return JsonResponse(data)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for saving a JavaScript object into a JSON file

Let's discuss how to save the following data: myJSONtable into a JSON file using the following method: fs.writeFile('./users.json', JSON.stringify(myJSONtable, null, 4), 'utf-8', function (err) { if (err) throw err ...

"Implementing x2js in your project on-the-fly with the help

Hey there, does anyone have the link for x2js that they could share with me? I'm interested in loading this JavaScript file dynamically. I tried using the code below but it didn't work: EffectaJQ.ajax({ async: false, url: "https ...

Devbridge AutoComplete leveraging Ajax fails to populate suggested options

Currently, I have an autocomplete field that triggers a server search based on the fullname in a database, with the response being in JSON format. The issue arises when using the JSON server response instead of a local array, as the suggestion list does n ...

Issue with assigning material to a three.js object!

Being new to three.js, I have recently started exploring it. However, I am facing an issue where I am unable to assign a material to an object. var objloader=new THREE.OBJLoader(); var material=new THREE.MeshNormalMaterial(); objloader.load('man.obj& ...

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

Utilizing the document.createDocumentFragment() method along with innerHTML for manipulating a Document Object Model (

I am currently in the process of creating a document fragment using the code below: let fullHTMLDocument = '<!doctype html> <html><head></head><body><h1>hello world</h1></body></html>'; let f ...

Tips for transferring date values in an ajax request to a web application handler

I am currently working on plotting a graph between two dates using Google Charts. My goal is to send date values to the controller, which is implemented with webapp2. However, I am facing difficulties in figuring out how to send date values to the controll ...

Creating transparency effect on objects using Physical Material in THREE.js

Is there a way to showcase a translucent PNG texture behind a transparent Physical Material in THREE.js? It seems like currently, THREE.js does not display the translucent texture through the Physical Material. I discovered that when I set transparent: fa ...

Executing a JavaScript script from a C# script: A step-by-step guide

Greetings all! I am currently engrossed in a school project that requires me to populate a paragraph element with data from a table in my database. Initially, I attempted to achieve this task using JavaScript, but due to the connection script being in C#, ...

Clicking the identical button on multiple overlapping elements using Selenium and Node.js

Working with Selenium has presented a challenge when trying to close multiple HTML elements that share the same "close" button and overlap each other. The initial approach of looping through them individually to close seemed unsuccessful. The first step i ...

What significance does the slash hold in a package name when using require for an npm package?

When we "require" non-local NodeJS modules, what does the slash in the module name signify? For instance: from the GitHub page of the ShellJS npm module (link: https://github.com/shelljs/shelljs#javascript) require('shelljs/global'); requir ...

What is the method for defining a monkey patched class in a TypeScript declarations file?

Let's say there is a class called X: class X { constructor(); performAction(): void; } Now, we have another class named Y where we want to include an object of class X as a property: class Y { xProperty: X; } How do we go about defining ...

How can a modern browser retrieve a json.gz file without relying on external libraries?

What can be done to let the browser know that a json.gz file is compressed JSON, for example: {"abc":1}, and automatically unpack it into a JavaScript object? I attempted this approach, but it was not successful: https://en.wikipedia.org/wiki/JS ...

How can PHP be integrated with MaterializeJS for autocomplete functionality?

Here is my PHP code snippet: <?php require_once __DIR__ . '/../inc/_puredb.php'; $query = $db->prepare("SELECT user_name FROM users"); $query->execute(); if($query->rowCount() > 0) { $rows = array(); while($res = $quer ...

Displaying country-specific API details (such as capital and currency) in a card container when selecting a country from a dropdown menu

My objective is to display the card information for South Africa as the default value, even before entering any country's name into the search bar input field or selecting a specific country from the provided list. I am utilizing the restcountries API ...

What is the best way to neatly import multiple images in Next.js?

I have a dilemma involving 10 images located in my public directory that I need to use in a component. Instead of individually importing each image like this: import imgurl1 from "../../public/celsius.gif"; import imgurl2 from "../../public/ ...

Is there a way to make this variable function properly within the google.maps.LatLng() method?

I've been working on a function that goes through some JSON data and retrieves latlong information to be displayed inside google.maps.LatLng(). The issue I'm facing is that I keep getting a null return and I can't seem to identify the reason ...

Scroll horizontally through the number field in Chrome

I have configured a number input field with the text aligned to the right. Scenario: While testing, I discovered that selecting the entire text or using the middle mouse button to scroll within the input field allows for a slight leftward scrolling of ab ...

Extract data from JSON object

My JSON object is called idAndNames.json; [ { "id":"1", "name":"name1"}, { "id":"2", "name":"name2"}, { "id":"3", "name":"name3"} ] I'm looking to filter it by ID and name function applyFilter(id, valueItem) { return id <= valueIte ...