django 在REACT中为PUT/PATCH使用Fetch对我不起作用

q3aa0525  于 2023-11-20  发布在  Go
关注(0)|答案(2)|浏览(135)

Hello在我的React App中,我使用这个特定的comportement来处理修改(状态更改激活/停用)

const handleActifEspece = (index, statutActif) => {
        let especeAActiver = especes.find(espece => espece.id === index)
        especeAActiver.actif =  statutActif
        console.log(JSON.stringify(especeAActiver))
        fetch(`http://localhost:8000/api/especes/${index}`, {
            method: 'PUT',
            headers: { 'Content-type': 'application/json; charset=UTF-8',},
            body: JSON.stringify(especeAActiver)
        })
        .then(response => response.json())
        .then(data => {
            snackBar.openSnackbar("Espèce modifiée !")
            setSnackMode('success');
            setEspeces([...especes, data])
        })
        .catch(error => {
            console.error("Erreur pendant l'activation de l'espèce", error);
            snackBar.openSnackbar("Espèce non modifiée !")
            setSnackMode('error');
        })
    };

字符串
当我点击日志中的按钮时,我得到了特定的数据:ma var的JSON字符串是:
{“id”:40,“nom”:“Test 6”,“gaf”:false,“actif”:true,“instance”:{“id”:1}}
我得到了错误500我使用DjangoRestFramework来处理API当我复制过去的dat的URL,并得到了放置这里是错误的Swagger:

{
    "instance": [
        "Incorrect type. Expected pk value, received dict."
    ]
}


[编辑]
View.py

class EspeceView(viewsets.ModelViewSet):
    serializer_class = EspeceSerializer
    queryset = Espece.objects.all()


Serializers.py

class EspeceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Espece
        fields = ('id', 'nom', 'gaf', 'actif', 'instance',)

    def to_representation(self, instance):
        self.fields['instance'] = InventaireSerializer(read_only=True)
        return super(EspeceSerializer, self).to_representation(instance)


登录终端(Django服务器运行)

[03/Nov/2023 12:25:15] "OPTIONS /api/especes/40 HTTP/1.1" 200 0
Internal Server Error: /api/especes/40
Traceback (most recent call last):
  File "folders/Pepiniere_V2/.venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "folders/Pepiniere_V2/.venv/lib/python3.11/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.process_response(request, response)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "folders/Pepiniere_V2/.venv/lib/python3.11/site-packages/django/middleware/common.py", line 108, in process_response
    return self.response_redirect_class(self.get_full_path_with_slash(request))
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "folders//Pepiniere_V2/.venv/lib/python3.11/site-packages/django/middleware/common.py", line 87, in get_full_path_with_slash
    raise RuntimeError(
RuntimeError: You called this URL via PUT, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining PUT data. Change your form to point to localhost:8000/api/especes/40/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
[03/Nov/2023 12:25:15] "PUT /api/especes/40 HTTP/1.1" 500 68422


它在POST(add)和POST中工作得很好,但在PUT或PATCH中就不行了:(请帮助;)

gmxoilav

gmxoilav1#

按照traceback说的做:将 * espiceAActiver * 从

{"id":40,
 "nom":"Test 6",
 "gaf":false,
 "actif":true,
 "instance":{"id":1}}

字符串

{"id":40,
 "nom":"Test 6",
 "gaf":false,
 "actif":true,
 "instance":1}

6tdlim6h

6tdlim6h2#

我发现.这是“/”后的网址调用..我的错,我没有读所有的错误消息.它的作品现在很好!感谢弗拉德告诉我添加traceback ;)

[...]
const handleActifEspece = (index, statutActif) => {
        let especeAActiver = especes.find(espece => espece.id === index)
        especeAActiver.actif =  statutActif
        console.log(JSON.stringify(especeAActiver))
        fetch(`http://localhost:8000/api/especes/${index}/`, {
[...]

字符串
/是需要后url调用.再次感谢

相关问题