Django Vue.js Axios PUT Не разрешено 405
Я разрабатываю небольшой проект по управлению запасами. Я пытаюсь обновить количество товара на складе, когда какой-то товар снимается с продажи. Я использую Axios и функцию .put(), и когда я отправляю запрос, он говорит, что 405 не разрешено. Я не могу понять, в чем проблема. Я отправляю идентификатор продукта в бэкенд и использую его для идентификации продукта, количество которого на складе я хочу обновить. Надеюсь, вы сможете указать мне на мои ошибки и научить меня, как заставить это работать.
Вот представления из Django:
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)
Это 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()),
]
а это мой скрипт из Vue.js:
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)
})
}
},
}
Я решил проблему. Проблема заключалась в моем запросе Axios, а также в модели View. Вот решение для тех, кто столкнулся с такой же проблемой.
Вот мой 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)
и Axios:
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)
})
}