为什么Django不接受React Native应用程序发送的文件?

发布于 2025-01-25 21:06:06 字数 7012 浏览 2 评论 0原文

我正在为后端服务器使用Django,并为移动应用程序进行反应本机,我正在尝试从那里上传图像,但它给出了500服务器错误。

views.py表格django

@api_view(['POST'])
def setFakeProfile(request):
    if request.method=='POST':
        user = Token.objects.get(key = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]).user
        profile = Profile.objects.get(user=user)
        fakeProfiles = profile.fakeProfiles.filter(isProfileReadyToUse=False)
        print(request.data)
        print(request.FILES)
        if fakeProfiles.exists():
            fakeProfile = fakeProfiles[0]
            fakeProfile.displayName = request.data["displayName"]
            fakeProfile.profilePicture = request.FILES.get('profilePicture')
            fakeProfile.isProfileReadyToUse = True
            fakeProfile.save()
            return Response({'status':'success', 'id':fakeProfile.id})
        else:
            return Response({'status':'failed', "message":"First select the chating platform."})


        return Response({
                'status':'success',
            })
        
    return Response({'status':'failed'})

我遇到的错误就在那里。我知道这个错误,我还尝试了许多方法来解决它,但仍然不知道如何解决。

{'_parts': [['displayName', 'name'], ['profilePicture', {'cancelled': False, 'type': 'image', 'uri': 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png', 'width': 1692, 'height': 1692}]]}
app_1  | <MultiValueDict: {}>
app_1  | Internal Server Error: /setFakeProfile/
app_1  | Traceback (most recent call last):
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1  |     response = get_response(request)
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1  |     return view_func(*args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1  |     return self.dispatch(request, *args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
app_1  |     response = self.handle_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1  |     self.raise_uncaught_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1  |     raise exc
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1  |     response = handler(request, *args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1  |     return func(*args, **kwargs)
app_1  |   File "/app/core/views.py", line 318, in setFakeProfile
app_1  |     fakeProfile.displayName = request.data["displayName"]
app_1  | KeyError: 'displayName'
app_1  | [03/May/2022 12:32:32] "POST /setFakeProfile/ HTTP/1.1" 500 91167
app_1  | {'_parts': [['displayName', 'name'], ['profilePicture', 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png']]}
app_1  | <MultiValueDict: {}>
app_1  | Internal Server Error: /setFakeProfile/
app_1  | Traceback (most recent call last):
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1  |     response = get_response(request)
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1  |     return view_func(*args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1  |     response = self.handle_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1  |     self.raise_uncaught_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1  |     raise exc
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1  |     response = handler(request, *args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1  |     return func(*args, **kwargs)
app_1  |   File "/app/core/views.py", line 318, in setFakeProfile
app_1  |     fakeProfile.displayName = request.data["displayName"]
app_1  | KeyError: 'displayName'
app_1  | [03/May/2022 12:32:52] "POST /setFakeProfile/ HTTP/1.1" 500 91167

让我们看看本机代码。

const [displayName, setDisplayName] = useState("");
    const [displayImage, setDisplayImage] = useState(null);
    const [error, setError] = useState('');

    const pickImage = async () => {
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.All,
          allowsEditing: true,
          aspect: [1, 1],
          quality: 1,
        });
    
        console.log(result);
    
        if (!result.cancelled) {
            setDisplayImage({
                ...result,
                uri: Platform.OS === 'ios' ? result.uri.replace('file://', '') : result.uri,
            });
        }
      };


    const onSubmit = async () =>{
        console.log("submit");

        const formData = new FormData();

        formData.append('displayName', displayName);
        formData.append('profilePicture', displayImage);


        await axios.post(
                `${baseUrl}setFakeProfile/`,
                formData,
                {
                    headers: {
                        // 'Content-Type': 'multipart/form-data',
                        // 'Accept': 'multipart/form-data',
                        'Content-Type': 'application/json',
                        'Accept': "application/json",
                        'Authorization': `Token ${await getData('token')}` 
                    }  
                }        
            ).then(res=>{
                if (res.data.status==="success"){
                    dispatch(setFakeProfileIdToOpen(res.data.id));
                    navigation.navigate('FakeAccount');
                }else{
                    setError(res.data.message);
                    console.log(res.data.message);
                }
            }).catch(err=>console.log(err));
    }

我还尝试了评论的代码(含义'content-type':“ multipart/form-data”),但它仍然无法正常工作。

I am using Django for the Backend Server and React Native for a mobile app I am trying to upload an image from there but it is giving a 500 server error.

Views.py form Django

@api_view(['POST'])
def setFakeProfile(request):
    if request.method=='POST':
        user = Token.objects.get(key = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]).user
        profile = Profile.objects.get(user=user)
        fakeProfiles = profile.fakeProfiles.filter(isProfileReadyToUse=False)
        print(request.data)
        print(request.FILES)
        if fakeProfiles.exists():
            fakeProfile = fakeProfiles[0]
            fakeProfile.displayName = request.data["displayName"]
            fakeProfile.profilePicture = request.FILES.get('profilePicture')
            fakeProfile.isProfileReadyToUse = True
            fakeProfile.save()
            return Response({'status':'success', 'id':fakeProfile.id})
        else:
            return Response({'status':'failed', "message":"First select the chating platform."})


        return Response({
                'status':'success',
            })
        
    return Response({'status':'failed'})

The error that I am getting is there. I knew about the error and I also tried a lot of ways to resolve it but not still don't know how to fix it.

{'_parts': [['displayName', 'name'], ['profilePicture', {'cancelled': False, 'type': 'image', 'uri': 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png', 'width': 1692, 'height': 1692}]]}
app_1  | <MultiValueDict: {}>
app_1  | Internal Server Error: /setFakeProfile/
app_1  | Traceback (most recent call last):
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1  |     response = get_response(request)
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1  |     return view_func(*args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1  |     return self.dispatch(request, *args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
app_1  |     response = self.handle_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1  |     self.raise_uncaught_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1  |     raise exc
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1  |     response = handler(request, *args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1  |     return func(*args, **kwargs)
app_1  |   File "/app/core/views.py", line 318, in setFakeProfile
app_1  |     fakeProfile.displayName = request.data["displayName"]
app_1  | KeyError: 'displayName'
app_1  | [03/May/2022 12:32:32] "POST /setFakeProfile/ HTTP/1.1" 500 91167
app_1  | {'_parts': [['displayName', 'name'], ['profilePicture', 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png']]}
app_1  | <MultiValueDict: {}>
app_1  | Internal Server Error: /setFakeProfile/
app_1  | Traceback (most recent call last):
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1  |     response = get_response(request)
app_1  |   File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1  |     return view_func(*args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1  |     response = self.handle_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1  |     self.raise_uncaught_exception(exc)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1  |     raise exc
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1  |     response = handler(request, *args, **kwargs)
app_1  |   File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1  |     return func(*args, **kwargs)
app_1  |   File "/app/core/views.py", line 318, in setFakeProfile
app_1  |     fakeProfile.displayName = request.data["displayName"]
app_1  | KeyError: 'displayName'
app_1  | [03/May/2022 12:32:52] "POST /setFakeProfile/ HTTP/1.1" 500 91167

Let's see the React Native code.

const [displayName, setDisplayName] = useState("");
    const [displayImage, setDisplayImage] = useState(null);
    const [error, setError] = useState('');

    const pickImage = async () => {
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.All,
          allowsEditing: true,
          aspect: [1, 1],
          quality: 1,
        });
    
        console.log(result);
    
        if (!result.cancelled) {
            setDisplayImage({
                ...result,
                uri: Platform.OS === 'ios' ? result.uri.replace('file://', '') : result.uri,
            });
        }
      };


    const onSubmit = async () =>{
        console.log("submit");

        const formData = new FormData();

        formData.append('displayName', displayName);
        formData.append('profilePicture', displayImage);


        await axios.post(
                `${baseUrl}setFakeProfile/`,
                formData,
                {
                    headers: {
                        // 'Content-Type': 'multipart/form-data',
                        // 'Accept': 'multipart/form-data',
                        'Content-Type': 'application/json',
                        'Accept': "application/json",
                        'Authorization': `Token ${await getData('token')}` 
                    }  
                }        
            ).then(res=>{
                if (res.data.status==="success"){
                    dispatch(setFakeProfileIdToOpen(res.data.id));
                    navigation.navigate('FakeAccount');
                }else{
                    setError(res.data.message);
                    console.log(res.data.message);
                }
            }).catch(err=>console.log(err));
    }

I also tried with the commented code (means 'Content-Type': 'multipart/form-data' ) but it is still not working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文