为什么Django不接受React Native应用程序发送的文件?
我正在为后端服务器使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论