Having trouble updating information using axios and vue-python

I encountered a problem while attempting to update an element from my form. Here is the code snippet:

<script setup>
    const updateSupply = async () => {
        console.log("Test");
        errors.value = ""
        try {
            await axios.put("http://127.0.0.1:49146/" + "supply");
        } catch (e) {
            if (e.response.status === 422) {
                for (const key in e.response.data.errors) {
                    errors.value = e.response.data.errors
                }
            }
        }
    };

const { destroySupply, updateSupply, updateClick } = useSupply();

const saveSupply = async () => {
  // console.log("Test");
  await updateSupply();
  // supply_id:this.supply_id,
};
</script>

<template>
<!-- Modal -->
  <CardBoxModal_JTO
    v-model="updateModalActive"
    title="Update supply"
    has-close
  >
    <form @submit.prevent="saveSupply">
      <CardBox>
        <FormField label="Noms & Email">
          <FormControl
            id="supply_name"
            v-model="form.supply_name"
            name="supply_name"
            :icon="mdiAccount"
            placeholder="name supply"
            required
          />
          <FormControl
            id="supply_email"
            v-model="form.supply_email"
            name="supply_email"
            type="email"
            :icon="mdiMail"
            placeholder="Email supply"
            required
          />
        </FormField>

        <!-- Buttons footer -->
        <BaseButtons class="flex justify-center">
          <BaseButton
            class="mr-2"
            type="submit"
            color="jt_orders"
            label="Update"
          />
          <BaseButton
            class="ml-2"
            type="reset"
            color="danger"
            outline
            label="Cancel"
          />
        </BaseButtons>
      </CardBox>
    </form>
  </CardBoxModal_JTO>


</template>

Here is the Django code snippet:

# SupplyApi
@csrf_exempt
def supplyApi(request,id=0):
    if request.method=='GET':
        supplies = Supplies.objects.all()
        supplies_serializer = SupplySerializer(supplies,many=True)
        return JsonResponse(supplies_serializer.data,safe=False)
    elif request.method == 'POST':
        supply_data = JSONParser().parse(request)
        supplies_serializer = SupplySerializer(data=supply_data)
        if supplies_serializer.is_valid():
            supplies_serializer.save()
            return JsonResponse("Added Successfully",safe=False)
        return JsonResponse("Failed to Add",safe=False)
    elif request.method =='PUT':
        supply_data = JSONParser().parse(request)
        supply = Supplies.objects.get(supply_id=supply_data['supply_id'])
        supplies_serializer = SupplySerializer(supply,data=supply_data)
        if supplies_serializer.is_valid():
            supplies_serializer.save()
            return JsonResponse("Updated Successfully",safe=False)
        return JsonResponse("Failed to Update")
    elif request.method == 'DELETE':
        supply = Supplies.objects.get(supply_id=id)
        supply.delete()
        return JsonResponse("Deleted Successfully",safe=False)

After triggering the update action, I encounter the error

[HTTP/1.1 500 Internal Server Error 527ms]
. The specific Django server error message:

Internal Server Error: /supply
...
JSON parse error - Expecting value: line 1 column 1 (char 0)

All functions as expected with my storeSupply function which operates correctly.

<script>
const storeSupply = async (data) => {
        errors.value = ""
        try {
            await axios.post("http://127.0.0.1:49146/" + "supply", data);
        } ...
    }
</script>

Seeking advice on what may be causing this issue. Thank you in advance for your assistance.

Answer №1

It appears that the PUT request from your Vue.js component does not include any data. The updateSupply function in your Django view is expecting to receive JSON data in the request, which may be causing the error you are encountering.

To rectify this issue, consider including the data you wish to update in the PUT request. Here is an example of how you can modify your code:

const updateSupply = async () => {
    console.log("Test");
    errors.value = ""
    try {
        await axios.put("http://127.0.0.1:49146/" + "supply", form.value);
    } catch (e) {
        if (e.response.status === 422) {
            for (const key in e.response.data.errors) {
                errors.value = e.response.data.errors
            }
        }
    }
};

Answer №2

I managed to resolve my issue by making some changes in the backend code. Initially, I updated the backend by including the following line:

supply = Supplies.objects.get(supply_id=id)
instead of
supply = Supplies.objects.get(supply_id=supply_data["supply_id"])
. Please refer to the complete code snippet below Django code

elif request.method == "PUT":
    supply_data = JSONParser().parse(request)
    supply = Supplies.objects.get(supply_id=id)
    supplies_serializer = SupplySerializer(supply, data=supply_data)
    if supplies_serializer.is_valid():
       supplies_serializer.save()
       return JsonResponse("Updated Successfully", safe=False)
    return JsonResponse("Failed to Update")

After that, I made adjustments to the storeSupply or updateSupply function as follows:

const updateSupply = async (id) => {
  console.log("Access successfully");
  await axios
    .put("http://127.0.0.1:49146/" + "supply/" + id, {
      supply_address: form.supply_address,
      supply_city: form.supply_city,
      supply_email: form.supply_email,
      supply_name: form.supply_name,
      supply_phone: form.supply_phone,
      supply_zip_code: form.supply_zip_code,
    })
    .then((response) => {
      console.log(response);
      // alert(response.data); Put toast here
      location.reload();
    });
};

These modifications resolved the issue, and everything is now functioning correctly. Many thanks to everyone who contributed to solving this problem.

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

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

stop executing the code if an error occurs repeatedly

Is there a method I can use to track errors based on how many times they occur? For example, if I am handling an error using exceptions as shown below: except NoSuchElementException: driver.find_element_by_tag_name('body').send_keys(Keys.PA ...

What is the best method for extracting tr tags with varying column specifications (e.g. 1 = td and 2 = a within td)?

I am currently facing an issue with scraping a table that contains specific rows. Here is the relevant HTML code: <tr> <td align="center" class="hell" width="20%"> <b>1 : 0</b> </td> <td class="hell"> <a href ...

Is it possible to integrate a JavaScript library into the Vue prototype?

I've recently integrated ProgressBar.js library into my app, which is built using vue and laravel with laravel mix. After installing ProgressBar.js via npm install, I am unsure how to incorporate it into my .vue files. I'm considering adding it t ...

Issue with URL parsing arises in Nuxt.js2 when executing the "npm run build" command

While working on my project with Nuxt 2, everything runs smoothly when I use npm run dev. However, I encounter an error when I run npm run build, which you can view here: Despite removing packages, individual pages, and components, as well as rebuilding G ...

The thread messaging queue is experiencing a shortage of messages being properly delivered

I've developed a function that scans files, organizes them with specific data, and then transfers them to a message queue for transmission through a socket by a separate thread: for filename in os.listdir(os.getcwd()): ... reading and numerical s ...

Issue with datetime64[ns] on the x axis in the index cannot be resolved

I am facing an issue with my dataframe structure, which is as follows: Open time Open High Low Close 4_EMA 20_EMA Position 0 2021-03-30 12:00:00 1848.86 1849.04 1826.05 1830.61 1830.610000 1830.610000 Na ...

Error: OpenAI's transcription API has encountered a bad request issue

const FormData = require('form-data'); const data = new FormData(); console.log('buffer: ', buffer); console.log('typeof buffer: ', typeof buffer); const filename = new Date().getTime().toString() + '.w ...

Exploring the Power of Nuxt's asyncData Feature for Handling Multiple Requests

Within my application, there is a seller page showcasing products listed by the specific seller. Utilizing asyncData to retrieve all necessary data for this page has been beneficial in terms of SEO. asyncData ({params, app, error }) { return app.$axi ...

Leveraging a component as a property of an object in Vue version 3

I'm trying to figure out if there's a way to use a Component as a property in Vue 3. Consider the TypeScript interface example below: import type { Component } from 'vue' interface Route { url: string icon: Component name: ...

Is Pykka about slow actors?

I'm currently delving into Actor-concurrency in Python to enhance my understanding. I decided to use pykka, but upon testing, it seems to be over twice as slow compared to a regular function. The code is just for testing purposes and not intended to ...

Adjust the size of the Chrome browser window using Selenium Python to perfectly match the screen dimensions

Is there a way to fully maximize the Chrome browser window size to perfectly fit the screen? I attempted to do so using the driver.maximize_window() function, but it only maximized the height and not the width. The versions I am currently working with are ...

How can I structure two for loops within a list comprehension in Python?

Here are two lists that I currently have: tags = [u'man', u'you', u'are', u'awesome'] entries = [[u'man', u'thats'],[ u'right',u'awesome']] I am looking to extract entries fr ...

Issues with Vue JS: the closing tag linting function is not functioning properly

Has anyone experienced this particular issue before? https://i.stack.imgur.com/p8dM3.png I've checked all my outputs and there are no error messages. I'm currently going through my plugins one by one to troubleshoot. If anyone has encountered t ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

Python code for sorting numbers into designated buckets

Is there a way in Python to assign buckets to numbers falling within specific ranges (0-0.99, 1.0-1.99, 2.0-2.99, etc.) when dealing with float type values? The code below is causing an error due to the data type. How can this be achieved alternatively? ...

Tips for creating a uniform background image for both the header and the overall design in Vuetify

take a look at this image as an example https://i.stack.imgur.com/k8UVC.jpg kindly respond to the question using Vuetify exclusively ...

Is there a way I can link a variable to a URL for an image?

Creating v-chip objects with dynamic variable names and images is causing an issue. The image source string depends on the name provided, but when I bind the name to the source string, the image fails to load. Despite trying solutions from a similar questi ...

Solving the Issue of Python Selenium Unable to Click on the Desired Element

I'm facing an issue with my Python Selenium script where it seems to be clicking on the element behind the target element instead of the actual target. Specifically, when trying to interact with a 'drop-down menu', I inadvertently end up cli ...

Mysterious behavior observed when utilizing a vectorized partial function with `numpy` and `functools`

I am in the process of vectorizing a partial function that operates on two lists as arguments and performs operations on corresponding elements from each list using the zip function. However, I have come across some unexpected behavior. Take a look at the ...