I'm getting POST http://localhost:8000/api/reports/ 415 (Unsupported Media Type)
when I try to submit the form from React and I don't understand what's the problem.
Here's the code.
models.py
class Report(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
description = models.TextField()
address = models.CharField(max_length=500)
reporter_first_name = models.CharField(max_length=250)
reporter_last_name = models.CharField(max_length=250)
reporter_email = models.CharField(max_length=250)
reporter_phone = models.CharField(max_length=250)
report_image_1 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
report_image_2 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
report_image_3 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
date = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ('-date',)
def __str__(self):
return self.description
I also tried to put default values for images, but I still get the error.
serializers.py
class ReportSerializer(serializers.ModelSerializer):
categoryName = CategorySerializer(many=False, read_only=True, source='category')
class Meta:
model = Report
fields = '__all__'
views.py
class ManageReports(viewsets.ModelViewSet):
serializer_class = ReportSerializer
parser_classes = [MultiPartParser, FormParser]
def get_object(self, queryset=None, **kwargs):
id = self.kwargs.get('pk')
return get_object_or_404(Report, id=id)
def get_queryset(self):
return Report.objects.all()
This is the code responsible for the submit.
report.js
const initialPostData = Object.freeze({
category: '',
address: '',
description: '',
reporter_first_name: '',
reporter_last_name: '',
reporter_email: '',
reporter_phone: '',
});
const [postData, updatePostData] = useState(initialPostData);
const [postImage1, setPostImage1] = useState({image: null});
const [postImage2, setPostImage2] = useState({image: null});
const [postImage3, setPostImage3] = useState({image: null});
const handleChange = (e) => {
if([e.target.name] == 'reporter_image_1') {
setPostImage1({
image: e.target.files[0],
});
} else if([e.target.name] == 'reporter_image_2') {
setPostImage2({
image: e.target.files[0],
});
} else if([e.target.name] == 'reporter_image_3') {
setPostImage3({
image: e.target.files[0],
});
} else if([e.target.name] == 'category') {
updatePostData({
...postData,
[e.target.name]: e.target.value,
});
} else {
updatePostData({
...postData,
[e.target.name]: e.target.value.trim(),
});
}
};
const handleSubmit = async(e) => {
e.preventDefault();
let formData = new FormData();
formData.append('category', postData.category);
formData.append('address', postData.address);
formData.append('description', postData.description);
formData.append('reporter_first_name', postData.reporter_first_name);
formData.append('reporter_last_name', postData.reporter_last_name);
formData.append('reporter_email', postData.reporter_email);
formData.append('reporter_image_1', postImage1.image);
formData.append('reporter_image_2', postImage2.image);
formData.append('reporter_image_3', postImage3.image);
const submitForm = await submitReport(formData);
And here's the submitReport
API
API.js
const axiosInstance = axios.create({
baseURL: 'http://localhost:8000/api/',
timeout: 5000,
headers: {
Authorization: accessToken
? 'JWT ' accessToken
: null,
'Content-Type': 'application/json',
accept: 'application/json',
},
});
// Submit Report Form
const submitReport = async(formData) => {
const { data } = await axiosInstance.post('reports/', {...formData });
return data;
}
These should be all the files needed to understand what's going on.
Thanks in advance.
CodePudding user response:
Your parser_classes
attribute on viewset is wrong. If you want to accept JSON format in request body you need to include JSONParser
in your parser_classes
attribute.
See the related section from here in DRF docs.
CodePudding user response:
I found the solution, I was using the spread operator in the submitReport
function, but instead I don't need to use it, so:
API.js
// Submit Report Form
const submitReport = async(formData) => {
const { data } = await axiosInstance.post('reports/', {...formData });
return data;
}
becomes
// Submit Report Form
const submitReport = async(formData) => {
const { data } = await axiosInstance.post('reports/', formData);
return data;
}