Django app with Vue.js integration is throwing a 405 error for Axios PUT request

I have a project in progress for managing inventory on a small scale. One of the functionalities I'm working on involves updating the stock quantity when a product is withdrawn. I've encountered an issue while using Axios and the .put() function, as it returns a 405 error message indicating that the action is not allowed. I'm passing the product ID to the backend to identify the specific product whose stock needs to be updated. I would appreciate any guidance on identifying and correcting my mistakes so that I can successfully implement this feature.

Below is the relevant code snippet from Django's views:

class materialWithdraw(APIView):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.BasePermission]

    def update(self, request, *args, **kwargs):
        serializer = WithdrawFormSerializer(data=request.data)
        if serializer.is_valid():
            material_id = serializer.validated_data['id']
            quantity_to_withdraw = serializer.validated_data['quantity']
            withdrawn_material = Listing.objects.get(id=material_id)
            withdrawn_material.quantity = withdrawn_material.quantity - quantity_to_withdraw
            serializer.save(quantity=withdrawn_material.quantity)
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

This section contains the URLs defined in urls.py:

urlpatterns = [
    path('all-materials/', views.allMarketingMaterials.as_view()),
    path('all-medical-lines/', views.allMedicalLines.as_view()),
    path('gastroenterologia/', views.gastroenterologiaMaterials.as_view()),
    path('withdraw/', views.materialWithdraw.as_view()),
]

Lastly, here is an excerpt from my Vue.js script:

export default {
  name: "Gastroenterologia",
  components: {},
  data() {
    return {
      gastroenterologiaMaterials: [],
      quantity: 0,
      id:'',
    }
  },
  mounted() {
    document.title = "Gastroenterologia";
    this.getGastroenterologiaMaterials()
  },
  methods: {
    getGastroenterologiaMaterials() {
      axios
        .get('/api/v1/gastroenterologia/')
        .then(response => {
          this.gastroenterologiaMaterials = response.data
          console.log(this.gastroenterologiaMaterials)
        })
        .catch(error => {
          console.log(error)
        })
    },
    chooseMaterial(index) {
      const materialName = document.querySelector('#material-name')
      const materialType = document.querySelector('#material-type')
      materialName.textContent = this.gastroenterologiaMaterials[index].title
      materialType.textContent = this.gastroenterologiaMaterials[index].type
      this.id = this.gastroenterologiaMaterials[index].id
    },

    materialWithdraw() {

      console.log(this.title)

      const data = {
        'quantity': this.quantity,
        'id': this.id,
      }

      axios
        .put('/api/v1/withdraw/', data)
        .then(response => {
          return response
        })
        .catch(error => {
          console.log(error)
        })
    }


  },
}

Answer №1

The issue has been successfully resolved by fixing the Axios request and the View model. For those encountering a similar problem, here is the solution:

See below for my Views.py:

class materialWithdraw(APIView):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.BasePermission]

    def put(self, request, pk, format=None):
        withdrawn_material = Listing.objects.get(id=pk)
        serializer = WithdrawFormSerializer(withdrawn_material, data=request.data)

        if serializer.is_valid():
            quantity_to_withdraw = serializer.validated_data['quantity']
            withdrawn_material.quantity = withdrawn_material.quantity - quantity_to_withdraw
            print('Success', quantity_to_withdraw, withdrawn_material.quantity)
            serializer.save(quantity=withdrawn_material.quantity)
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

And here is the Axios part of the code:

materialWithdraw() {

      console.log(this.title)

      const data = {
        'quantity': this.quantity,
      }

      axios
        .put(`/api/v1/withdraw/${this.id}`, data)
        .then(response => {
          return response
        })
        .catch(error => {
          console.log(error)
        })
}

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

Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli. Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like: 'use strict'; var testingThing = testingThing || {}; testingThing. ...

JavaScript causing Axios network error

Recently, I've started exploring the combination of axios and stripe in my project but unfortunately, I have encountered some challenges. Whenever I attempt to initiate a post request using axios, an error pops up which looks like this: https://i.sta ...

saving user's scroll position in a Vue 3 app

Encountering an issue with my Vue application. It comprises more than 40 pages, and the problem lies in the browser caching the scroll position. As a result, when users navigate from one page to another, the browser displays the scroll position of the prev ...

Infinite loop always occurs with Ui-router FromState being constantly reset

My page is experiencing continuous refreshing and calling $stateChangeStart after the first call to $state.go. I believe this issue may be related to the StateProvider configuration. Can anyone offer suggestions on what might be going wrong? Check out thi ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

Tips for displaying the sum of a grouped field in the balloonText using Amchart

I recently started working with Amcharts and I am seeking advice on what I may be doing incorrectly. Below is the snippet of my JavaScript code: var chartData1 = []; generateChartData(); function generateChartData() { var month = new Array( ...

Steps for displaying a website within a specific Div using HTML

I'm trying to set up a website to open within a specific <div> tag, like the example shown in this link: Responsive. Can anyone spot what I'm doing incorrectly? <html> <head> <script> function mobile320() { ...

The controller in my template is not being passed by the $routeProvider

I attempted to dynamically load a template in Angular using ngRoute... However, I encountered an issue with the following code: (app.js route configuration) app.config(function($routeProvider) { $routeProvider.when("/password", { templateUrl ...

What is the best way to transfer files using vue.js 2?

Here is the structure of my Vue component: <template> <div class="modal" tabindex="-1" role="dialog"> <form method="post" :action="baseUrl+'/product/edit'" files="true"> ... <input type="f ...

Ajax in action

I've encountered a problem with my JavaScript function. The function is supposed to display an alert when called without AJAX, but it's not working when I include AJAX. Here's the function: function stopSelected(){ var stop=document ...

What is Causing The Card to Not Expand?

I wanted to enhance my project by incorporating a responsive card template, so I turned to one of the templates on CodePen for help. However, after copying the code into my own platform, I encountered an issue where the card wouldn't expand when click ...

Instructions on how to trigger a function after adding HTML content to the directive

When working with the viewBannerCtrl controller and using the "customTable" directive, I encountered an issue. I am unable to access the "VBC.bannerAlert()" function from the directive even though I tried appending the code to the directive. Confusingly, I ...

`On mouseup event, changing specific text`

I've been working on a real-time HTML highlighter that surrounds selected text with span elements containing a background property. Check out the fiddle here: https://jsfiddle.net/4hd2vrex/ The issue arises when users make multiple selections, leadi ...

Axios POST request in VueJS blocked due to Cross-Origin Request restrictions

Having trouble sending a POST request when submitting a form due to CORS issues. I keep encountering the following errors: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/lists/contacts ...

Is there a way to access or delete a randomly generated document ID in Firestore?

Need help with code to delete an item (current method not working) const docRef = firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid) docRef.collection('tasks').doc(this.task.id).delete() ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

Using require to access an Immediately Invoked Function Expression variable from another file in Node.js

File 1 - Monitor.js var MONITOR = (function () { // Code for Monitoring return { doThing: function() { doThing(); } }; })(); File 2 - Test.js var monitor = require('../public/js/monitor.js'); I am trying to access the doThing() funct ...

There was an issue with the Vuejs Router that prevented the property '$emit' from being read due to a TypeError because

I am facing an issue with a router configuration like this: { path: 'user', redirect: '/user', name: 'user', component: { render(c) { return c('router-view', { on ...

Instructions on invoking a function from one controller within another controller

Is it possible to invoke a function from one controller in another controller? I attempted the following but encountered failure: <div ng-app="MyApp"> <div ng-controller="Ctrl1"> <button ng-click="func1()">func1</button> ...

What is the best way to combine the average hours, minutes, seconds, and milliseconds in JavaScript?

I am seeking guidance on how to calculate the average of three different times in JavaScript. In the scenario presented below, the average of the three times is calculated as 01:42:22:566. <form action="/action_page.php"> <label for= ...