无法从axios和vue-python更新数据。

huangapple go评论97阅读模式
英文:

Can't update data from axios and vue-python

问题

I have a problem when I want to update an element from my form.

  1. <script setup>
  2. const updateSupply = async () => {
  3. console.log("Test");
  4. errors.value = ""
  5. try {
  6. await axios.put("http://127.0.0.1:49146/" + "supply");
  7. } catch (e) {
  8. if (e.response.status === 422) {
  9. for (const key in e.response.data.errors) {
  10. errors.value = e.response.data.errors
  11. }
  12. }
  13. }
  14. };
  15. const { destroySupply, updateSupply, updateClick } = useSupply();
  16. const saveSupply = async () => {
  17. // console.log("Test");
  18. await updateSupply();
  19. // supply_id:this.supply_id,
  20. };
  21. </script>
  22. <template>
  23. <!-- Modal -->
  24. <CardBoxModal_JTO
  25. v-model="updateModalActive"
  26. title="Update supply"
  27. has-close
  28. >
  29. <form @submit.prevent="saveSupply">
  30. <CardBox>
  31. <FormField label="Noms & Email">
  32. <FormControl
  33. id="supply_name"
  34. v-model="form.supply_name"
  35. name="supply_name"
  36. :icon="mdiAccount"
  37. placeholder="name supply"
  38. required
  39. />
  40. <FormControl
  41. id="supply_email"
  42. v-model="form.supply_email"
  43. name="supply_email"
  44. type="email"
  45. :icon="mdiMail"
  46. placeholder="Email supply"
  47. required
  48. />
  49. </FormField>
  50. <!-- Buttons footer -->
  51. <BaseButtons class="flex justify-center">
  52. <BaseButton
  53. class="mr-2"
  54. type="submit"
  55. color="jt_orders"
  56. label="Update"
  57. />
  58. <BaseButton
  59. class="ml-2"
  60. type="reset"
  61. color="danger"
  62. outline
  63. label="Cancel"
  64. />
  65. </BaseButtons>
  66. </CardBox>
  67. </form>
  68. </CardBoxModal_JTO>
  69. </template>

The Django code:

  1. # SupplyApi
  2. @csrf_exempt
  3. def supplyApi(request, id=0):
  4. if request.method == 'GET':
  5. supplies = Supplies.objects.all()
  6. supplies_serializer = SupplySerializer(supplies, many=True)
  7. return JsonResponse(supplies_serializer.data, safe=False)
  8. elif request.method == 'POST':
  9. supply_data = JSONParser().parse(request)
  10. supplies_serializer = SupplySerializer(data=supply_data)
  11. if supplies_serializer.is_valid():
  12. supplies_serializer.save()
  13. return JsonResponse("Added Successfully", safe=False)
  14. return JsonResponse("Failed to Add", safe=False)
  15. elif request.method == 'PUT':
  16. supply_data = JSONParser().parse(request)
  17. supply = Supplies.objects.get(supply_id=supply_data['supply_id'])
  18. supplies_serializer = SupplySerializer(supply, data=supply_data)
  19. if supplies_serializer.is_valid():
  20. supplies_serializer.save()
  21. return JsonResponse("Updated Successfully", safe=False)
  22. return JsonResponse("Failed to Update")
  23. elif request.method == 'DELETE':
  24. supply = Supplies.objects.get(supply_id=id)
  25. supply.delete()
  26. return JsonResponse("Deleted Successfully", safe=False)

Somehow I get this error [HTTP/1.1 500 Internal Server Error 527ms]. And the Django server error:

  1. Internal Server Error: /supply
  2. Traceback (most recent call last):
  3. File "C:\Python311\Lib\site-packages\rest_framework\parsers.py", line 64, in parse
  4. return json.load(decoded_stream, parse_constant=parse_constant)
  5. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  6. # More error details...

PS: Below is my code for the storeSupply which works very well:

  1. <script>
  2. const storeSupply = async (data) => {
  3. errors.value = ""
  4. try {
  5. await axios.post("http://127.0.0.1:49146/" + "supply", data);
  6. } catch (e) {
  7. if (e.response.status === 422) {
  8. for (const key in e.response.data.errors) {
  9. errors.value = e.response.data.errors
  10. }
  11. }
  12. }
  13. }
  14. </script>

What did I do wrong?
Thank you for your help.

英文:

I have problem when I want to update an element from my form.
here is my code:

  1. <script setup>
  2. const updateSupply = async () => {
  3. console.log("Test");
  4. errors.value = ""
  5. try {
  6. await axios.put("http://127.0.0.1:49146/" + "supply");
  7. } catch (e) {
  8. if (e.response.status === 422) {
  9. for (const key in e.response.data.errors) {
  10. errors.value = e.response.data.errors
  11. }
  12. }
  13. }
  14. };
  15. const { destroySupply, updateSupply, updateClick } = useSupply();
  16. const saveSupply = async () => {
  17. // console.log("Test");
  18. await updateSupply();
  19. // supply_id:this.supply_id,
  20. };
  21. </script>
  22. <template>
  23. <!-- Modal -->
  24. <CardBoxModal_JTO
  25. v-model="updateModalActive"
  26. title="Update supply"
  27. has-close
  28. >
  29. <form @submit.prevent="saveSupply">
  30. <CardBox>
  31. <FormField label="Noms & Email">
  32. <FormControl
  33. id="supply_name"
  34. v-model="form.supply_name"
  35. name="supply_name"
  36. :icon="mdiAccount"
  37. placeholder="name supply"
  38. required
  39. />
  40. <FormControl
  41. id="supply_email"
  42. v-model="form.supply_email"
  43. name="supply_email"
  44. type="email"
  45. :icon="mdiMail"
  46. placeholder="Email supply"
  47. required
  48. />
  49. </FormField>
  50. <!-- Buttons footer -->
  51. <BaseButtons class="flex justify-center">
  52. <BaseButton
  53. class="mr-2"
  54. type="submit"
  55. color="jt_orders"
  56. label="Update"
  57. />
  58. <BaseButton
  59. class="ml-2"
  60. type="reset"
  61. color="danger"
  62. outline
  63. label="Cancel"
  64. />
  65. </BaseButtons>
  66. </CardBox>
  67. </form>
  68. </CardBoxModal_JTO>
  69. </template>

The Django code

  1. # SupplyApi
  2. @csrf_exempt
  3. def supplyApi(request,id=0):
  4. if request.method=='GET':
  5. supplies = Supplies.objects.all()
  6. supplies_serializer = SupplySerializer(supplies,many=True)
  7. return JsonResponse(supplies_serializer.data,safe=False)
  8. elif request.method == 'POST':
  9. supply_data = JSONParser().parse(request)
  10. supplies_serializer = SupplySerializer(data=supply_data)
  11. if supplies_serializer.is_valid():
  12. supplies_serializer.save()
  13. return JsonResponse("Added Successfully",safe=False)
  14. return JsonResponse("Failed to Add",safe=False)
  15. elif request.method =='PUT':
  16. supply_data = JSONParser().parse(request)
  17. supply = Supplies.objects.get(supply_id=supply_data['supply_id'])
  18. supplies_serializer = SupplySerializer(supply,data=supply_data)
  19. if supplies_serializer.is_valid():
  20. supplies_serializer.save()
  21. return JsonResponse("Updated Successfully",safe=False)
  22. return JsonResponse("Failed to Update")
  23. elif request.method == 'DELETE':
  24. supply = Supplies.objects.get(supply_id=id)
  25. supply.delete()
  26. return JsonResponse("Deleted Successfully",safe=False)

Somehow i get this error [HTTP/1.1 500 Internal Server Error 527ms].
And the django server error :

  1. IInternal Server Error: /supply
  2. Traceback (most recent call last):
  3. File "C:\Python311\Lib\site-packages\rest_framework\parsers.py", line 64, in parse
  4. return json.load(decoded_stream, parse_constant=parse_constant)
  5. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  6. File "C:\Python311\Lib\site-packages\rest_framework\utils\json.py", line 31, in load
  7. return json.load(*args, **kwargs)
  8. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  9. File "C:\Python311\Lib\json\__init__.py", line 293, in load
  10. return loads(fp.read(),
  11. ^^^^^^^^^^^^^^^^
  12. File "C:\Python311\Lib\json\__init__.py", line 359, in loads
  13. return cls(**kw).decode(s)
  14. ^^^^^^^^^^^^^^^^^^^
  15. File "C:\Python311\Lib\json\decoder.py", line 337, in decode
  16. obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  17. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  18. File "C:\Python311\Lib\json\decoder.py", line 355, in raw_decode
  19. raise JSONDecodeError("Expecting value", s, err.value) from None
  20. json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
  21. During handling of the above exception, another exception occurred:
  22. Traceback (most recent call last):
  23. File "C:\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
  24. response = get_response(request)
  25. ^^^^^^^^^^^^^^^^^^^^^
  26. File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
  27. response = wrapped_callback(request, *callback_args, **callback_kwargs)
  28. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  29. File "C:\Python311\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view
  30. return view_func(*args, **kwargs)
  31. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  32. File "C:\Users\rt-enterprises\OneDrive\RTSOFTT\PROJECTS\Python Projects\JT_ORDER-FILES\jt_orders\jt_orders_app\views.py", line 42, in supplyApi
  33. supply_data = JSONParser().parse(request)
  34. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  35. File "C:\Python311\Lib\site-packages\rest_framework\parsers.py", line 66, in parse
  36. raise ParseError('JSON parse error - %s' % str(exc))
  37. rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0)

PS : Below is my code for the storeSupply which works very well.

  1. <script>
  2. const storeSupply = async (data) => {
  3. errors.value = ""
  4. try {
  5. await axios.post("http://127.0.0.1:49146/" + "supply", data);
  6. } catch (e) {
  7. if (e.response.status === 422) {
  8. for (const key in e.response.data.errors) {
  9. errors.value = e.response.data.errors
  10. }
  11. }
  12. }
  13. }
  14. </script>

What did I do wrong ?
Thank you for you help.

答案1

得分: 0

你的Vue.js组件在PUT请求中没有发送任何数据。在updateSupply函数中,Django视图期望解析来自传入请求的JSON,这就是为什么你会遇到这个错误。

让我们尝试在PUT请求中包括你想要更新的数据,例如:

  1. const updateSupply = async () => {
  2. console.log("Test");
  3. errors.value = ""
  4. try {
  5. await axios.put("http://127.0.0.1:49146/" + "supply", form.value);
  6. } catch (e) {
  7. if (e.response.status === 422) {
  8. for (const key in e.response.data.errors) {
  9. errors.value = e.response.data.errors
  10. }
  11. }
  12. }
  13. };
英文:

You're not sending any data in your PUT request from your Vue.js component. In the updateSupply function, and Django view expects to parse JSON from the incoming request which is why you have this error.

lets try to include the data you want to update in the PUT request, for example:

  1. const updateSupply = async () => {
  2. console.log("Test");
  3. errors.value = ""
  4. try {
  5. await axios.put("http://127.0.0.1:49146/" + "supply", form.value);
  6. } catch (e) {
  7. if (e.response.status === 422) {
  8. for (const key in e.response.data.errors) {
  9. errors.value = e.response.data.errors
  10. }
  11. }
  12. }
  13. };

答案2

得分: 0

I found the solution to my problem.
First I changed the backend by adding:
supply = Supplies.objects.get(supply_id=id) in place of supply = Supplies.objects.get(supply_id=supply_data["supply_id"]).

then I modified the storeSupply or updateSupply function by

  1. const updateSupply = async (id) => {
  2. console.log("Access successfully");
  3. await axios
  4. .put("http://127.0.0.1:49146/" + "supply/" + id, {
  5. supply_address: form.supply_address,
  6. supply_city: form.supply_city,
  7. supply_email: form.supply_email,
  8. supply_name: form.supply_name,
  9. supply_phone: form.supply_phone,
  10. supply_zip_code: form.supply_zip_code,
  11. })
  12. .then((response) => {
  13. console.log(response);
  14. // alert(response.data); Put toast here
  15. location.reload();
  16. });
  17. };

and it works now without problem, thank you all for your help.

英文:

I found the solution to my problem.
First I changed the backend by adding:
supply = Supplies.objects.get(supply_id=id) in place of supply = Supplies.objects.get(supply_id=supply_data["supply_id"]).
Please see full code below
Django code

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

then I modified the storeSupply or updateSupply function by

  1. const updateSupply = async (id) => {
  2. console.log("Access successfully");
  3. await axios
  4. .put("http://127.0.0.1:49146/" + "supply/" + id, {
  5. supply_address: form.supply_address,
  6. supply_city: form.supply_city,
  7. supply_email: form.supply_email,
  8. supply_name: form.supply_name,
  9. supply_phone: form.supply_phone,
  10. supply_zip_code: form.supply_zip_code,
  11. })
  12. .then((response) => {
  13. console.log(response);
  14. // alert(response.data); Put toast here
  15. location.reload();
  16. });
  17. };

and it works now without problem, thank you all for your help.

huangapple
  • 本文由 发表于 2023年5月14日 01:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定