I am building my first react-native app with a Django backend. In order for my app to work properly, I need to upload an image from react-native to Django and then save it to a model. But when I try to send the image, I get "raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'profileImage'."
here's my code: frontend
const [ sentI, setSentI ] = useState(null)
const sendI = (image) => {
const formData = new FormData()
image_data = {
uri : image.uri,
name : "profileImage",
type : 'image/jpg'
}
if (image != null){
formData.append( 'profileImage', image_data,)
setSentI(formData)
console.log('recieved')
}
console.log(formData)
}
const showImagePicker = async () => {
// Ask the user for the permission to access the media library
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("You've refused to allow this appp to access your photos!");
return;
}
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
// Explore the result
console.log(result);
if (!result.cancelled) {
await setProfileImage(result);
console.log(result.uri);
sendI(result);
}
}
const image = () => {
fetch(`http://192.168.5.234:8000/home/imagetest/`, {
method: 'POST',
body: {
sentI
},
})
.then( res => res.json())
.then( res => {
console.log(res)
})
.catch( error => console.log(error))
}
return (
<View style={styles.scroll}>
<ScrollView style={styles.scroll}>
<Button onPress={showImagePicker} title="Select an image" />
<View style={styles.imageContainer}>
{
profileImage !== null ? <Image
source={{ uri: profileImage.uri }}
style={styles.image}
/>
:
<Image style={styles.image}
source={require('../assets/emptyProfile.png')}
/>
}
</View>
</ScrollView>
</View>
)
here's my backend-
@csrf_exempt
def imagetest(request):
if request.method == "POST":
image = request.POST['profileImage']
print(image)
CodePudding user response:
The error is saying that there is no keyword profileImage
in the request.POST
dictionary-like object.
In your javascript image
-function, you send the object literal instead of the object formData
itself.
Try changing it to:
fetch(`http://192.168.5.234:8000/home/imagetest/`, {
method: 'POST',
body: sentI,
})
I would also suggest you try to use request.POST.get("profileImage", False)
in Django, as discussed here: https://stackoverflow.com/a/5895670/6383431