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

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

Can't update data from axios and vue-python

问题

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

<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>

The Django code:

# 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)

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

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

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

<script>
const storeSupply = async (data) => {
        errors.value = ""
        try {
            await axios.post("http://127.0.0.1:49146/" + "supply", data);
        } catch (e) {
            if (e.response.status === 422) {
                for (const key in e.response.data.errors) {
                    errors.value = e.response.data.errors
                }
            }
        }
    }
</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:

<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>

The Django code

# 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)

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

IInternal Server Error: /supply
Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\rest_framework\parsers.py", line 64, in parse
    return json.load(decoded_stream, parse_constant=parse_constant)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\rest_framework\utils\json.py", line 31, in load
    return json.load(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
           ^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\__init__.py", line 359, in loads
    return cls(**kw).decode(s)
           ^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rt-enterprises\OneDrive\RTSOFTT\PROJECTS\Python Projects\JT_ORDER-FILES\jt_orders\jt_orders_app\views.py", line 42, in supplyApi
    supply_data = JSONParser().parse(request)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\rest_framework\parsers.py", line 66, in parse
    raise ParseError('JSON parse error - %s' % str(exc))
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.

<script>
const storeSupply = async (data) => {
        errors.value = ""
        try {
            await axios.post("http://127.0.0.1:49146/" + "supply", data);
        } catch (e) {
            if (e.response.status === 422) {
                for (const key in e.response.data.errors) {
                    errors.value = e.response.data.errors
                }
            }
        }

    }
</script>

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

答案1

得分: 0

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

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

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
            }
        }
    }
};
英文:

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:

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
            }
        }
    }
};

答案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

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();
    });
};

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

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")

then I modified the storeSupply or updateSupply function by

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();
    });
};

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:

确定